针对错误元素的更改事件激发的JQuery

JQuery on change event firing for the wrong element

本文关键字:JQuery 事件 错误元素      更新时间:2023-09-26

我有两个<select>元素:select.exerciseType#moduleTopic,每个元素都有自己的处理程序包在document上。我认为重要的是要知道select.exerciseType是普通的,并且可能有多个。他们的活动是:

$(document).ready(function() {
    $(document).on("change", $("select.exerciseType"), function(e) {
        <!--Code not really important-->
    }
    $(document).on("change", $("#moduleTopic"), function(e) {
        <!--Code not really important-->
    }
}

我的问题是,当我在其中一个选择中更改所选选项时,这两个事件都会触发。为什么on()函数中的选择器不起作用,我如何使它起作用?

jQuery的语法。处理程序上的语法为.on( events [, selector ] [, data ], handler ),其中第二个参数为string

在您的情况下,由于它不是string,因此它被省略,并且event总是在到达所选元素时触发!

$(document).ready(function() {
  $(document).on("change", "select.exerciseType", function(e) {});
  $(document).on("change", "#moduleTopic", function(e) {});
});

你能用这个代码代替吗:

$("#moduleTopic").change(function() {
 // code executes here
});

编辑---

您可以使用类名,并通过在函数中使用$(this)来检测正在更改的<select>

您不需要document.ready,您也只需要指定选择器,而不是检索它。即

// class example
$(document).on("change", "select.exerciseType", function(e) {
    // Code not really important
});
// ID example
$(document).on("change", "#moduleTopic", function(e) {
    // Code not really important
});