javascript - 为什么事件委托(delegate)不能与 jquery on() 一起使用

标签 javascript jquery jquery-events event-delegation

我正在使用最新的 jQuery,它表示 .live() 已被弃用,应该使用 .on() 代替。 我在将点击事件附加到按钮时遇到问题。我动态修改按钮值,应该能够处理这两种情况

<input type="text" ><input id="button_1" type="button" value="add" >
<input type="text"> <input id="button_2" type="button" value="add">

$('[id^="button_"]').on("click", "input", function() {
    $(this).val("delete");
    
    $('#button_'+$(this).attr('id').split('_')[1]).attr('id', 'delButton_'+$(this).attr('id').split[1]);
                                                     
});

$('[id^="delButton_"]').on("click", "input", function() {
    $(this).val("add");
    
    $('#delButton_'+$(this).attr('id').split('_')[1]).attr('id', 'button_'+$(this).attr('id').split[1]);
    
});

这是演示:jsfiddle

最佳答案

您只能将事件委托(delegate)给祖先 元素,但您正在尝试委托(delegate)给同级元素。 (实际上,我不确定你在做什么!)

所以如果你的标记是

<div class="buttonContainer">
    <input type="text" ><input id="button_1" type="button" value="add" >
</div>

你可以使用

$('.buttonContainer').on("click", "input", function() {
    // here, "this" will be the clicked input
});

上面的代码会将对文本输入和按钮的点击委托(delegate)给它们的父 div。单击任何元素将触发该函数。

如果您只想定位按钮,请更改传递给 .on 的选择器:

$('.buttonContainer').on("click", '[id^="button_"]', function() {
    // here, "this" will be the clicked button
});

关于javascript - 为什么事件委托(delegate)不能与 jquery on() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15510773/

相关文章:

jquery - 尝试阻止默认点击并运行函数

javascript - 如何模拟 `angular.element`

javascript - 脚本在 jsfiddle 中工作而不是在静态文件中?

带有 setInterval 的 Javascript 动画不起作用

javascript - 切换按钮来控制按钮

jquery - 如何检查css属性是否设置?

javascript - 仅在上一次交互完成后递增(回调)

php - 使用值形式下拉菜单?

jquery - Phonegap 中的绑定(bind)

jquery - 为什么这个 Javascript (jQuery) 不会进入无限循环?