如何在jquery中创建元素后调用函数?

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

例:

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

你是如何创建元素的?

如果您在静态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('
');

然后你可以这样做:

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

但这并不重要 – 因为它是同步的(这意味着下一行代码将无法运行,直到它将元素添加到DOM中……除非你正在加载图像等)所以你可以做:

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

但实际上,说你可以这样做:

 $('
', {id:'mydiv'}).appendTo('body').css({backgroundColor:'red'});

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

因此,如果您有

    并动态创建新的

  • 项目,则可以在$(document).ready()中将选择器连接到事件处理程序,以便将所有

  • 元素连接起来对于那个事件。

    这是一个演示live的jsFiddle示例。

    希望这可以帮助。

    你可以试试这段代码

     $('body').on('click', '#btn', function() { $($('
    ').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; } 
         Test    

    有时,对于在您自己的脚本之外创建/加载的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 }); 

    在元素创建后,查看.live()最好的,

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

    然后添加一个新元素:

     $('body').append('
    Another target
    ');
     $("
    ").appendTo("#parent").each(function(){ console.log("I have been created!"); });

    最直接的是在创建元素后直接调用回调:)