![](/img/trans.png)
[英]How to search text from page with next and previous functionality in jquery
[英]Getting & error(unnatural functionality ) while search a text from page in jquery?
我正在從頁面搜索文本。 一切順利。 但是只有一個問題,當用戶搜索&時,它還會搜索並附加amp數據。 你能告訴我為什么會發生嗎?
這是我的小提琴: http : //jsfiddle.net/ravi1989/wjLmx/22/
請輸入&,然后單擊“搜索”,然后再次單擊“搜索”,然后搜索,然后找到問題。
function searchAndHighlight(searchTerm, selector) {
if (searchTerm) {
//var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
//var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
var selector = selector || "#realTimeContents"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm, "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches != null && matches.length > 0) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
//Remove the previous matches
$span = $('#realTimeContents span');
$span.replaceWith($span.html());
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
$('.match:first').addClass('highlighted');
var i=0;
$('.next_h').off('click').on('click', function () {
i++;
if(i >= $('.match').length)
i=0;
$('.match').removeClass('highlighted');
$('.match').eq(i).addClass('highlighted');
});
$('.previous_h').off('click').on('click', function () {
i--;
if(i < 0)
i=$('.match').length-1;
$('.match').removeClass('highlighted');
$('.match').eq(i).addClass('highlighted');
});
if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).on('click', '.searchButtonClickText_h', function (event) {
$(".highlighted").removeClass("highlighted").removeClass("match");
if (!searchAndHighlight($('.textSearchvalue_h').val())) {
alert("No results found");
}
});
在HTML中,要獲取字符&
,請使用字符實體: &
。 因此,在搜索HTML文本時,您一定會找到它們(您可能還會找到<
和
以及其他字符實體)。 您的代碼采用了以下HTML:
&
...並將其更改為:
<span class="match highlighted">&</span>amp;
...所以您看到的是amp;
在文本中。
這是該代碼的一般問題的特定示例。 不幸的是,我認為代碼采用的方法太復雜而無法糾正。 我認為,為了解決整個問題,您根本不必在HTML中進行替換。 而是循環遍歷匹配元素中的文本節點 ,並對它們的nodeValue
進行替換,它們將是普通字符串(僅包含&
等),而不是HTML編碼的實體。 你將不得不使用splitText
分割文本節點(兩次,之前和您要更換后的文字),然后把中間有點內span
您通過創建createElement
,插入span
在第二分割點前。
那將是通用的解決方案:不要嘗試在HTML上進行replace
。
現在,你可以很容易地解決這個特定的漏洞,通過把該行做的HTML替換之前: 小提琴
if (searchTerm === "&") {
searchTerm = "&";
searchTermRegEx = new RegExp(searchTerm, "ig");
}
...但是那不能解決一般問題。 解決一般問題可能需要徹底改變您的方法,使用文本節點等,如前所述。
旁注:您將用戶的搜索詞直接傳遞到RegExp
構造函數中。 您真的希望您的用戶正確鍵入正則表達式嗎? 例如,如果鍵入[
,則結果將是無效的正則表達式。 如果要從字面上搜索它們鍵入的內容,則必須不使用正則表達式,或者在正則表達式中轉義特殊字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.