[英]JQuery event dosen't work after .addClass
為什么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>
事件處理程序被添加到選擇當時匹配的元素,改變了選擇以后不會奇跡般地使事件處理工作。
您可以為此使用委托事件處理程序
$(document).ready(function(){
$(document).on("click", ".b", function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
但是,為什么要這樣做,似乎只有在懸停相同元素之后才能激活單擊處理程序,這是一種奇怪的模式,因為除非將鼠標懸停在該元素上,否則您無法單擊它?
嘗試這個
$("body")
.on('click', '.a', function (){
$(this).addClass("b");
})
.on('click', '.b', function (){
$(this).text("hello");
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.