gpt4 book ai didi

javascript - 添加新按钮时 jQuery 单击事件未触发

转载 作者:行者123 更新时间:2023-11-30 08:10:21 25 4
gpt4 key购买 nike

当我单击“显示”按钮时,将调用显示监听器并显示一个新的隐藏按钮。但为什么当我单击“隐藏”时隐藏按钮没有被调用?

 $('.myCss').append('<input type="button" class="show" value="Show"/>');

$('.show').on('click', function () {
console.log('show clicked');
$('.myCss').append('<input type="button" class="hide" value="Hide"/>');
});

$('.hide').on('click', function () {
console.log('hide clicked');
$('.myCss').append('<input type="button" class="show" value="Show"/>');
});

最佳答案

它与添加到页面的元素的顺序有关。如果您将隐藏代码放在显示代码中,它会起作用(尽管您应该检查您的逻辑):

$('.show').on('click', function() {
console.log('show clicked');
$('.myCss').append('<input type="button" class="hide" value="Hide"/>');
$('.hide').on('click', function() {
console.log('hide clicked');
$('.myCss').append('<input type="button" class="show" value="Show"/>');
});
});​

jsFiddle example

在您的原始代码中,将点击事件绑定(bind)到隐藏按钮的代码存在于实际的隐藏按钮之前,因此它实际上并未绑定(bind)到任何东西。通过将它移动到另一个代码块中,您可以延迟该 block 的执行。您也可以使用 .on() 将点击事件绑定(bind)到 DOM 中更高层的事件,但最终结果实际上基本相同。

来自 the docs :

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

关于javascript - 添加新按钮时 jQuery 单击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11264540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com