如果我运行搜索并突出显示文本:
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
highlightSearch();
}
});
function highlightSearch() {
$('span').removeClass('highlighted');
var text = document.getElementById("query").value;
var query = new RegExp("(\b" + text + "\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|</span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;
}
然后这部分代码停止工作:
$('.service-box').click(function(){
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
$('#popupWindow #contentBox').html($(this).html());
});
它不再注册。click()。我不知道出了什么问题。你能帮我解决这个问题吗?
谢谢!
您正在使用innerHTML
和来消除所有事件处理程序。如果您要使用它,请委托事件:
$(document).on("click", '.service-box', function(){
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
$('#popupWindow #contentBox').html($(this).html());
});
由于我不知道什么是静态父级,所以我使用了document
。请将其替换为静态父级的选择器。
它之所以不起作用,是因为您正在使用innerHTML
进行高亮显示,这会破坏该元素的事件,还会一次又一次地触发DOM的生成。
正因为如此,我开发了mark.js,这是一个用于搜索词或自定义正则表达式的关键字高亮器。