我想使用 jQuery 选择并返回搜索到的文本。
问题是; 部分文本可能位于或其他内联元素中,因此在此文本中<span>
搜索时: ,您不会得到任何匹配项,而文本对人们来说是不间断的。'waffles are tasty'
'I'm not sure about <i>cabbages</i>, but <b>waffles</b> <span>are</span> <i>tasty</i>, indeed.'
让我们以这个 HTML 为例:
<div id="parent">
<span style="font-size: 1.2em">
I
</span>
like turtles
<span>
quite a
</span>
lot, actually.
<span>
there's loads of
</span>
tortoises over there, OMG
<div id="child">
<span style="font-size: 1.2em">
I
</span>
like turtles
<span>
quite a
</span>
lot, actually.
TURTLES!
</div>
</div>
使用这个(或类似的)JavaScript:
$('div#parent').selectText({query: ['i like', 'turtles', 'loads of tortoises'], caseinsensitive: true}).each(function () {
$(this).css('background-color', '#ffff00');
});
//The (hypothetical) SelectText function would return an array of wrapped elements to chain .each(); on them
你会想要产生这个输出:(显然没有评论)
<div id="parent">
<span style="font-size: 1.2em">
<span class="selected" style="background-color: #ffff00">
I
</span> <!--Wrap in 2 separate selection spans so the original hierarchy is disturbed less (as opposed to wrapping 'I' and 'like' in a single selection span)-->
</span>
<span class="selected" style="background-color: #ffff00">
like
</span>
<span class="selected" style="background-color: #ffff00"> <!--Simple match, because the search query is just the word 'turtles'-->
turtles
</span>
<span>
quite a
</span>
lot, actually.
<span>
there's
<span class="selected" style="background-color: #ffff00">
loads of
</span> <!--Selection span needs to be closed here because of HTML tag order-->
</span>
<span class="selected" style="background-color: #ffff00"> <!--Capture the rest of the found text with a second selection span-->
tortoises
</span>
over there, OMG
<div id="child"> <!--This element's children are not searched because it's not a span-->
<span style="font-size: 1.2em">
I
</span>
like turtles
<span>
quite a
</span>
lot, actually.
TURTLES!
</div>
</div>
(假设的)SelectText
函数会将所有选定的文本包装在<span class="selected">
标签中,无论搜索的部分是否位于其他内联元素(如<span>
、'' 等)中。它不会搜索 child<div>
的内容,因为那不是内联元素。
有没有一个 jQuery 插件可以做这样的事情?(将搜索查询包装在 span 标签中并返回它们,不知道找到的文本的某些部分是否可能位于其他内联元素中?)
如果没有,如何创建这样的功能?这个函数有点像我正在寻找的东西,但是当找到的文本的一部分嵌套在其他内联元素中时,它不会返回所选范围和中断的数组。
任何帮助将不胜感激!