jQuery hover() and delegation



我正在使用jQuery创建一个增量搜索,我的其余代码运行良好,但当我试图只突出显示悬停在搜索中的元素时,它会开始突出显示所有其他元素。因为";p〃;标记是在HTML文件加载到浏览器后生成的,它们需要像我在代码上写的那样进行委派。我该怎么解决?

$(document).on("mouseover", "p", function (e) {
e.target.classList.add("highlight");
});

在将highlight类添加到悬停在上的元素之前,需要从所有其他<p>元素中删除该类

$(document).on("mouseover", "p", function(e) {
$("p").removeClass("highlight");
e.target.classList.add("highlight");
});
.highlight {
background: #FF0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is a paragraph with some text</p>
<p>This is a paragraph with some text</p>
<p>This is a paragraph with some text</p>
<p>This is a paragraph with some text</p>
<p>This is a paragraph with some text</p>

最新更新