gpt4 book ai didi

javascript - 元素 ID 更改后 JQuery Click() 不起作用

转载 作者:行者123 更新时间:2023-12-02 17:22:26 25 4
gpt4 key购买 nike

我尝试更改元素 id,然后用它做一些事情。这个脚本改变了id,但是点击不起作用。有 friend 提供了以下解决方案,但我想了解一下原因。

感谢您的帮助。

$('#some').hover(
function(){
$(this).attr('id', 'new');
}
);
$('#new').click(
function(){
$(this).fadeTo('slow' , 0.2);
}
);

解决方案:

$('#new').on('click',
function(){
$(this).fadeTo('slow' , 0.2);
}
);

但是为什么我不能直接使用“点击”?

更新:

谢谢大家的回答。这是后续行动:我使用“on”方法来启动点击事件。然后我可以在函数本身中包含相同的 id 以使其淡出吗?

代码:

       $('#new').live('click',
function(){
$('#new').fadeTo('slow' , 0.2);
}
);

我尝试了,但未能启动事件。如有任何解决方法建议,我们将不胜感激。

最佳答案

您正在动态更改 DOM 属性。事件附加到 DOM,而不是附加到 DOM 属性,如类、id、名称值等。为了使其正常工作,Event delegation解决方案是:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click','#new',function(){
$(this).fadeTo('slow' , 0.2);
});

关于javascript - 元素 ID 更改后 JQuery Click() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23804744/

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