我想使用jQuery選擇並返回搜索到的文本。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標籤中包裝搜索查詢並返回它們,無視發現文本的一部分是否可能位於其他內聯元素中?)
如果不是,那麼將如何創建這樣的函數? This function有點像我在找的東西,但是當找到的文本的部分嵌套在其他內聯元素中時,它不會返回所選跨度和斷點的數組。
任何幫助將不勝感激!
ID都是唯一的,所以你可能不希望包裹在所有選定的文本' '標籤,也許是一個班級?至於這個問題 - 爲什麼不通過所有的文本節點? –
對,忘了這個,讓我把它改成課。 這可能是一個好的開始,但是我怎麼會告訴文本/內聯節點的哪些部分應該被包裝,以及*他們應該如何包裝? – mickdekkers
http://stackoverflow.com/questions/5886858/full-text-search-in-html-ignoring-tags –