jQuery突出显示元素中跨标签的文本片段

mic*_*ers 5 javascript jquery text selection chaining

我想使用 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>
Run Code Online (Sandbox Code Playgroud)

使用这个(或类似的)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
Run Code Online (Sandbox Code Playgroud)

你会想要产生这个输出:(显然没有评论)

<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>
Run Code Online (Sandbox Code Playgroud)

(假设)SelectText函数会将所有选定的文本包装在<span class="selected">标签中,无论搜索的部分是否位于其他内联元素中,如<span>、'' 等。它不会搜索子元素<div>元素的内容,因为那不是内联元素。

是否有一个 jQuery 插件可以做这样的事情?(将搜索查询包装在 span 标签中并返回它们,不知道找到的文本的一部分是否可能位于其他内联元素中?)

如果没有,人们将如何创建这样一个功能?这个函数有点像我正在寻找的,但是当找到的文本的一部分嵌套在其他内联元素中时,它不会返回所选跨度和中断的数组。

任何帮助将不胜感激!

Rub*_*mov 4

小菜一碟!看到这个

折叠符号:

$.each(
    $(...).findText(...), 
    function (){
        ...
    }
);
Run Code Online (Sandbox Code Playgroud)

内联符号:

$(...).findText(...).each(function (){
        ...
    }
);
Run Code Online (Sandbox Code Playgroud)