gpt4 book ai didi

jquery代码只有在返回到控制台后才起作用

转载 作者:行者123 更新时间:2023-12-01 07:06:19 24 4
gpt4 key购买 nike

html

<span><a class="like-Unlike" href="">Like</a></span>

my.js

$(".like-Unlike").on('click',function (e) {

if ($(this).html() == "Like") {
$(this).html('Unlike');
}
else {
$(this).html('Like');
}
return false;
}
);

问题是:Like 按钮不能用作没有错误消息的切换按钮,但是当我将上述所有 javascript 返回到控制台后,它就可以工作了。

最佳答案

当您确认元素是动态附加的时,这些附加元素没有附加点击处理程序。要实现此目的,您需要使用事件委托(delegate)。您无需将事件处理程序附加到按钮,而是将其绑定(bind)到父元素,或者说body,然后修改on,例如

$('body').on('click', '.like-Unlike', function(e) {
e.preventDefault(); //don't use return false; has nothing to do with the issue though

var elm = $(this); //cache the element
(elm.text() == 'Like') ? elm.text('Unlike') : elm.text('Like'); //keeping it short
});

有关 event delegation 的更多信息

关于jquery代码只有在返回到控制台后才起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822023/

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