Javascript JQuery:如何根据给定的偏移量减少所选节点
我正在使用JQuery和DOM API来选择文本节点。选择文本节点后,需要根据字符偏移量再次重新选择。我不知道该怎么办 示例代码:Javascript JQuery:如何根据给定的偏移量减少所选节点,javascript,jquery,dom,Javascript,Jquery,Dom,我正在使用JQuery和DOM API来选择文本节点。选择文本节点后,需要根据字符偏移量再次重新选择。我不知道该怎么办 示例代码: var jCommentElm = jQuery("#345345"); //Select the original text var finalSelectedComment = Not sure how to do?; //Apply offset to select limited chars as per given count final
var jCommentElm = jQuery("#345345"); //Select the original text
var finalSelectedComment = Not sure how to do?; //Apply offset to select limited chars as per given count
finalSelectedComment .addClass("commentedtext"); //Apply CSS to highlight
编辑:
下面是我用来添加注释的示例标记。我有起始标记和注释偏移量。我使用起始标记选择标记后的完整文本,现在我想根据偏移量减少选择
<p > This is sample text. Few <?comment_marker 4?>chars may be selected together and mark as comment</p>
请帮助。试试这个:
HTML:
jQuery:
selectText('p');
function selectText(el) {
var el = $(el),
charEl = el.children("span[data-chars]"),
chars = parseInt(charEl.attr('data-chars')), //4
html = el.html(),
regex = /\<span data-chars=\"\d+\"\>\<\/span\>/gi,
index = html.search(regex),
newStr = html.replace(regex,''),
beg = newStr.substr(0,index),
mid = newStr.substr(index,chars),
end = newStr.substr(index + chars);
el.html(beg + '<span class="hi">'+mid+'</span>' + end);
}
这将寻找一个空白的跨度,作为HTML5 data-*元素的“标记”,该元素包含您想要突出显示的字符数,从该跨度之后开始
然后,它将缓存标记的索引,删除标记,将原始字符串切分为标记索引的开始部分、标记索引中的一部分加上要选择的字符数,然后是结束部分
然后将这三部分重新组装回父元素的innerHTML中,中间部分由一个不同的跨距包装,其中包含一个“hi”类,该类是“highlight”的缩写,其背景色属性为“yellow”或任何您喜欢的颜色
缺点
o空格算作一个字符
o返回并删除$'可能有点挑剔。您好。您能提供更多关于您要做什么的上下文吗?同时显示标记我正试图根据初始标记和给定的下一个字符数突出显示文本。我还在原始查询中添加了此详细信息。很难理解这个支离破碎的问题。不知道是什么,也不知道它来自哪里。除注释外,代码中任何位置均未显示偏移量或计数。一点也不清楚你想要完成什么
.hi {
background: yellow;
}
selectText('p');
function selectText(el) {
var el = $(el),
charEl = el.children("span[data-chars]"),
chars = parseInt(charEl.attr('data-chars')), //4
html = el.html(),
regex = /\<span data-chars=\"\d+\"\>\<\/span\>/gi,
index = html.search(regex),
newStr = html.replace(regex,''),
beg = newStr.substr(0,index),
mid = newStr.substr(index,chars),
end = newStr.substr(index + chars);
el.html(beg + '<span class="hi">'+mid+'</span>' + end);
}