Javascript JQuery事件dosen';课后不工作

Javascript JQuery事件dosen';课后不工作,javascript,jquery,Javascript,Jquery,为什么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> $(docu

为什么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>

$(文档).ready(函数(){
$(“.b”)。单击(函数(){
$(此).text(“你好”);
});
$(“.a”).mouseover(函数(){
$(本).addClass(“b”);
});
});

事件处理程序被添加到与选择器匹配的元素中,之后更改选择器不会神奇地使事件处理程序工作

您可以为此使用委托事件处理程序

$(document).ready(function(){
    $(document).on("click", ".b", function(){
       $(this).text("hello");
    });

    $(".a").mouseover(function(){
      $(this).addClass("b");
    });
});

但是为什么要这样做呢?只有在同一个元素悬停后才激活单击处理程序似乎是一种奇怪的模式,因为除非鼠标在上面,否则不可能单击它。

事件处理程序被添加到与选择器匹配的元素中。,稍后更改选择器不会神奇地使事件处理程序工作

您可以为此使用委托事件处理程序

$(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");
})
试试这个

$("body")
.on('click', '.a', function (){
   $(this).addClass("b");
})
.on('click', '.b', function (){
    $(this).text("hello");
})

委托事件,因此目标元素的选择器“在运行中”进行评估
id
不应以numberb开头在有人说相反的话之前,@unknowner说
不应
不应是正确的,但是它可以在HTML5中委托事件,所以目标元素的选择器是“动态”计算的。
id
不应该以numberb开头。在有人说相反的话之前,@UnknownUser说
不应该
不应该是正确的,但是它可以在HTML5中,我实际上想理解事件处理程序。这是解释我怀疑的简单方法。感谢you@rayashi-不客气,你也应该认真阅读事件,因为你接受了一个答案(并且不接受这个答案),这个答案甚至不使用鼠标悬停事件,而是一个点击事件?我实际上想了解事件处理程序。这是解释我怀疑的简单方法。感谢you@rayashi-不客气,您也应该认真阅读事件,因为您接受了一个答案(并且不接受这个答案),该答案甚至不使用鼠标悬停事件,而是单击事件?