gpt4 book ai didi

javascript - 创建后立即访问元素(无 setTimeout)

转载 作者:行者123 更新时间:2023-11-29 22:15:54 25 4
gpt4 key购买 nike

<分区>

我曾尝试寻找对此的答案,但我的措辞与使用 jQuery on() 方法寻找事件委托(delegate)的问题太相似了。因此,请不要对我的问题的措辞感到困惑。

鉴于我编写 jQuery 应用程序的经验,我实际上问这个问题感到很惭愧,但我必须承认我实际上并不知道这个问题的答案:-(

考虑一下:

// Create the div
$('#wrapper').prepend('<div id="test"></div>');

// Add content to the div, and attach events
// Only execute it once the div has been created though, so wait 20 milliseconds
setTimeout(function(){

// Add some button
$('#test').html('<button></button>');

// Add an event to the button
// ... after 20 milliseconds
setTimeout(function(){

// Attach the click event
$('#test button').click('dosomething');
});
},20);

在上面的代码中,我必须使用 setTimeout 来确保在选择它并添加内容、事件等之前已经创建了该元素...

我的问题很简单,有没有更好的方法来做到这一点?没有超时?

请注意,我并不是说,是否有更好的方法来编写上面的确切代码?我只是想知道是否有一种方法可以避免因指定原因而使用超时.

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