我试图寻找这个问题的答案,但我的措辞与使用 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
确保在选择元素并添加内容、事件等之前已创建元素...
我的问题很简单,有更好的方法吗?没有超时?
请注意,我的意思不是,是否有更好的方法来编写上面的确切代码?我只是想知道是否有一种方法可以避免因指定原因而使用超时.
最佳答案
这可能会有所帮助。
var _b = $('<button></button>');
$('#wrapper').prepend(_b);
_b.click(function(){
///do something
});
关于javascript - 创建后立即访问元素(不使用 setTimeout),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15165836/