我正在從頁面搜索文本。一切安好。但只有一個問題,當用戶搜索&搜索它也將數據與放追加。你能告訴我爲什麼會發生嗎?從jquery頁面搜索文本時出現錯誤(不自然的功能)?
這裏是我的小提琴: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");
}
});
* 「非自然的功能」 *? –
其實我從沒見過這個bug – Rohit
你在'.html()'和'.text()'之間切換。爲什麼? –