javascript - 创建后立即访问元素(不使用 setTimeout)

标签 javascript jquery timeout

我试图寻找这个问题的答案,但我的措辞与使用 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/

相关文章:

jQuery mouseon/mouseout 或悬停在 "on"绑定(bind)事件中

ajax - 超时期间的 fiddler 行为

java - Android https 长轮询 : Cannot receive response when polling interval is longer than 70 seconds

java - 套接字连接超时

javascript - 为离线 Web 应用程序存储图像数据(客户端存储数据库)

javascript - 两个淡入淡出切换效果之间的 Jquery 延迟

javascript 图像幻灯片(jquery 或 YUI)

jquery - 使用 mandrill 模板通过 JavaScript 发送电子邮件并隐藏收件人的电子邮件地址

javascript - 尝试使用 MediaHound API 时遇到问题

javascript - C语言中的二叉树装箱二维算法