2011-06-17 76 views
24

我想在元素创建完成后调用一个函数。有没有办法做到这一点?如何在jquery中创建元素后调用函数?

例子:

$("#myElement").ready(function() { 
    // call the function after the element has been loaded here 
    console.log("I have been loaded!"); 
}); 
+0

有什么背景? – 2011-06-17 13:04:48

+0

我不知道,我是在WYSIWYG编辑器里写的。我写这篇文章是为了让人们看到我期望的成就。 – 2011-06-17 13:05:22

+1

当你的意思是创建,你的意思是追加到DOM? – Tomgrohl 2011-06-17 13:05:48

回答

35

你如何创建元素之后?

如果您使用静态HTML创建它,那么只需使用.ready(handler).on("load", handler)。如果你使用的是AJAX,虽然这是另一个鱼的水壶。

如果你使用jQuery的load()功能再有就是你可以运行一个回调时被加载的内容:

$('#element').load('sompage.html', function(){ /* callback */ }); 

如果你使用jQuery的$.ajax$.get/$.post功能,然后有一个成功的回调即:

$.ajax({ 
    url: 'somepage.html', 
    success: function(){ 
    //callback 
    } 
}); 

如果你刚刚创建的元素并将其附加这样的:

$('body').append('<div></div>'); 

然后你就可以做到这一点,而不是:

$('<div />', { id: 'mydiv' }).appendTo('body').ready(function(){ /* callback */ }); 

但这并不重要 - 因为它是同步的(这意味着下一行代码将不会运行,直到它添加的元素到DOM反正... - 除非你加载图像和这样),所以你可以这样做:

$('<div />', { id: 'mydiv' }).appendTo('body'); 
$('#mydiv').css({backgroundColor:'red'}); 

但acctually,说,你可能只是这样做:

$('<div />', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'}); 
7

你可能想看看jQuery的live事件。您将事件处理程序附加到选择器,该选择器现在或者在DOM中创建其他元素之后匹配。

所以,如果你有一个<ul>和动态创建新<li>项目,在你的$(document).ready()你就可以将一个选择将事件处理程序,以便所有<li>元素将有线为该事件。

这是jsFiddle示例演示live

希望这会有所帮助。

-1

最直接的就是直接调用回调创建该元素:)

1

结账。生活()创建的元素之后最好,,

$('.clickme').live('click', function() { 
     // Live handler called. 
    }); 

    And then later add a new element: 

    $('body').append('<div class="clickme">Another target</div>'); 
0
$("<div id=\"elem\"></div>").appendTo("#parent").each(function(){ 

    console.log("I have been created!"); 

}); 
1

你可以试试这个代码

$('body').on('click', '#btn', function() { 
 
    $($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000); 
 
})
#old > div{ 
 
    width: 100px; 
 
    background: red; 
 
    color: white; 
 
    height: 20px; 
 
    font: 12px; 
 
    padding-left: 4px; 
 
    line-height: 20px; 
 
    margin: 3px; 
 
}
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <meta charset="utf-8"> 
 
    <title>Test</title> 
 
    <link rel="stylesheet" href="./index.css"> 
 
    </head> 
 
    <body> 
 
    <div> 
 
     <!-- Button trigger modal --> 
 
     <button type="button" id="btn">Create Div</button> 
 
     <div id="old"> 
 

 
     </div> 
 
    </div> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    </body> 
 
</html>

1

有时这是需要创建/加载的DOM元素在您自己的脚本之外,或者通过不同的js库或您的直接控制之外的事件。

对于这样的场景,我总是设置一个时间间隔,它定期检查目标元素是否存在,如果这是真的,则间隔删除自身并运行回调函数。

对于这一点,我有一个预定义的功能,我重用:

function runAfterElementExists(jquery_selector,callback){ 
    var checker = window.setInterval(function() { 
    //if one or more elements have been yielded by jquery 
    //using this selector 
    if ($(jquery_selector).length) { 

     //stop checking for the existence of this element 
     clearInterval(checker); 

     //call the passed in function via the parameter above 
     callback(); 
     }}, 200); //I usually check 5 times per second 
} 

//this is an example place in your code where you would like to 
//start checking whether the target element exists 
//I have used a class below, but you can use any jQuery selector 
runAfterElementExists(".targetElementClass", function() { 
    //any code here will run after the element is found to exist 
    //and the interval has been deleted 
    });