尝试以编程方式在UIWebView中选择文本时,setStart和setEnd抛出错误 [英] setStart and setEnd throwing error when trying to programmatically select text in UIWebView

查看:62
本文介绍了尝试以编程方式在UIWebView中选择文本时,setStart和setEnd抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我在UIWebView中使用的一些HTML:

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>

点击链接后,我想以编程方式选择UIWebView中的链接文本(所以这个是一个链接现在将使用蓝色iOS文本选择工具突出显示。这就是我在a标签的href中发送一些范围信息的原因。这是我用来尝试进行此程序化选择的电话:

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)"]];

这是javascript函数:

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);
}

正如您可以看到警报一样,它不会过去 range.setStart()调用而不会抛出错误。 Safari javascript调试器给出了这个错误:

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.

我尝试过很多不同的东西,但没有任何效果。我完全在我的智慧结束,并真的很感激有关如何做到这一点的一些见解。我开始怀疑甚至可以在UIWebView中以编程方式选择文本。我错了吗?有没有人这样做过?

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?

推荐答案

问题是你试图在第一个子节点中设置范围的边界< div> 元素,如果您的HTML确实看起来像在问题中那样,则为纯空格文本节点,或如果实际HTML中没有空格,则< span> 元素。在后一种情况下,即在元素中设置范围边界,偏移量表示边界之前元素的子节点数。

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.

这篇关于尝试以编程方式在UIWebView中选择文本时,setStart和setEnd抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆