我想使用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>
,''等)中。它不搜索子级<div>
内容,因为它不是内联元素。
是否有一个类似这样的jQuery插件?(将搜索查询包裹在span标记中并返回它们,而不考虑所找到的文本的某些部分是否可能位于其他内联元素中?)
如果没有,那么如何创建这样的功能呢?这个函数有点像我在寻找什么,但是当找到的文本的一部分嵌套在其他内联元素中时,它不会返回选定的跨度和中断数组。
任何帮助将不胜感激!
小菜一碟!看到这个。
折叠符号:
$.each(
$(...).findText(...),
function (){
...
}
);
内联符号:
$(...).findText(...).each(function (){
...
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句