选择元素未触发的on()方法

Aid*_*den 2 javascript jquery

我正在使用jQuery 1.9.0,我试图on()在选择内部更改选项时触发该方法.它有效,live()但我认为它可能是一些我没有看到的简单.

这是我的HTML:

<select class="select_exercise">
    <option class="option_exercise">Example 1</option>
    <option class="option_exercise">Example 2</option>
</select>
Run Code Online (Sandbox Code Playgroud)

和我的剧本:

$("option.option_exercise").on("change","option.option_exercise",function()
{
    alert("i am changing");
});
Run Code Online (Sandbox Code Playgroud)

这是小提琴

Jam*_*ice 6

.on()方法允许您在DOM树上方委托事件处理程序.我们的想法是将事件处理程序绑定到祖先元素,但只有在到达它的事件源自与选择器匹配的后代元素时才执行该处理程序.

在你的情况下,这将是这样的:

$(".select_exercise").on("change", ".option_exercise", function () {
// ^---- Probably no need to qualify the selectors with a tag name
    alert("i am changing");
});
Run Code Online (Sandbox Code Playgroud)

但是,给定您的示例代码,这将无法工作,因为option元素永远不会触发change事件(select尽管元素会).假设select元素从加载时开始在DOM中,您可以直接绑定到它:

$(".select_exercise").on("change", function () {
    alert("i am changing");
});
Run Code Online (Sandbox Code Playgroud)

如果它最初不在 DOM中,那么你必须委托更高的代码(我在body这里使用它作为一个例子.你应该尝试委托加载时在DOM中最接近的可能的祖先):

$("body").on("change", ".select_exercise", function () {
    alert("i am changing");
});
Run Code Online (Sandbox Code Playgroud)