为什么 div#1 不改变文本。我做错了什么?
<div id="1" class="a" style="width: 300px;height: 300px; background-color: #003366"></div>
<div id="2" class="b" style="width: 300px;height: 300px; background-color: #003366"></div>
<script>
$(document).ready(function(){
$(".b").click(function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
</script>
最佳答案
事件处理程序被添加到当时与选择器匹配的元素中,稍后更改选择器不会神奇地使事件处理程序工作。
您可以为此使用委托(delegate)事件处理程序
$(document).ready(function(){
$(document).on("click", ".b", function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
但是你为什么要这样做,这似乎是一种奇怪的模式,仅在悬停同一元素后才激活单击处理程序,因为除非鼠标悬停在它上面,否则你不可能单击它?
关于javascript - JQuery 事件在 .addClass 之后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22305947/