setStart and setEnd throwing error when trying to

2019-03-04 11:03发布

问题:

Here is some HTML that I am working with in my UIWebView:

<div id = "1">
    <span style = "background-color:red">
         <a href = "10&20">
              This is a link
         </a>
    </span>
</div>

Once the link is tapped, I want to programmatically select the link text in the UIWebView (so "This is a link" would now be highlighted with the blue iOS text selection tool). This is why I am sending some range information in the href of the a tag. This is the call I am using to try and make this programmatic selection:

//set content editable true
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"selectElementContentsInRange(document.getElementById('1'), 10, 20)"]];

And this is the javascript function:

function selectElementContentsInRange(el, first, second) {
    var range = document.createRange();
    alert("Makes it here");
    range.setStart(el.firstChild, first);
    alert("Doesn't make it here");
    range.setEnd(el.firstChild, second);

    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

And as you can see with the alerts, it doesn't make it past the range.setStart() call without throwing an error. The Safari javascript debugger is giving me this error:

IndexSizeError: DOM Exception 1: Index or size was negative, or greater than the allowed value.

I have tried so many different things, and nothing is working. I am completely at my wits end and would really appreciate some insight into how to do this. I am beginning to doubt that it is even possible to programmatically select text in UIWebView. Am I wrong? Has anyone done this?

回答1:

The problem is that you're trying to set the range's boundaries in the first child node of the <div> element, which is either a white space-only text node if your HTML really does look like it does in the question, or the <span> element if there is no white space in your actual HTML. In the latter case, i.e. setting a range boundary in an element, the offset represents the number of child nodes of the element preceding the boundary.