为什么事件委托不使用jquery on()

use*_*146 1 javascript jquery javascript-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]);

});
Run Code Online (Sandbox Code Playgroud)

这是演示:jsfiddle

bfa*_*tto 6

您只能将事件委托给祖先元素,但您正在尝试委托给兄弟姐妹.(实际上,我不确定你在做什么!)

所以如果你的标记是

<div class="buttonContainer">
    <input type="text" ><input id="button_1" type="button" value="add" >
</div>
Run Code Online (Sandbox Code Playgroud)

你可以用

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

上面将把文本输入和按钮的点击委托给他们的父div.单击任何元素将触发该功能.

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

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