我正在尝试自学 JQuery,但遇到了我认为是非常基本的问题。我最终想要的是在单击时更改样式的文本,在两个类之间来回切换。前半部分工作正常 - 当我第一次点击跨度时,新类(class)被分配。但是当我第二次点击时没有任何反应。我假设这是因为 JQuery 选择器仅将一次单击处理程序应用到当时与选择器匹配的元素。我如何修改我的代码,以便分配给特定类的点击处理程序将应用于所有具有该类的元素,而不管它们何时获得该类?
<html>
<head>
<title>My JQuery Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".spoiler").click(function() {
this.className = "revealed";
});
$(".revealed").click(function() {
this.className = "spoiler";
});
})
</script>
<style type="text/css">
.spoiler {
color: black;
background-color: black;
cursor:pointer
}
.revealed {
color: red;
background-color:white;
cursor:pointer
}
</style>
</head>
<body>
<h1>Caution, spoilers ahead</h1>
<p>At the end of <em>Soilent Green</em>, the main character reveals in dramatic fashion that "<span class="spoiler">Soilent Green is people!</span>"</p>
</body>
</html>
最佳答案
这是事件委托(delegate)的经典用例,您将事件挂接到容器元素(因为 click
冒泡),然后告诉 jQuery 仅在事件经过时触发您的处理程序通过匹配给定选择器的元素。单击发生时会完成检查,因此更新类会无缝进行:
$(document).ready(function () {
$(document.body).on("click", ".spoiler", function() {
this.className = "revealed";
});
$(document.body).on("click", ".revealed", function() {
this.className = "spoiler";
});
})
在该代码中,我使用的容器是页面主体,但通常会有一个容器更靠近您可以使用的相关元素。
更多信息 the documentation for on
.
另请注意,您可以通过 toggleClass
进一步简化它,它根据类是否已经存在来添加或删除类,并接受多个类名:
$(document).ready(function () {
$(document.body).on("click", ".spoiler, .revealed", function() {
$(this).toggleClass("spoiler revealed");
});
})
旁注:您不需要使用 ready
如果您将脚本标记放在 HTML 的末尾,就在结束 </body>
之前标签,通常是best practice除非有充分的理由去做其他事情。
关于javascript - 每当元素获得该类时,根据类附加点击处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988724/