我正在使用最新的 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/