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

问题描述:

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

I want to call a function after an element has been created. Is there a way to do this?

示例:

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


您是如何创建元素的?

如果您在静态HTML中创建它,那么只需使用 .ready(处理程序)。 on(load,handler)。如果你正在使用AJAX,那就是另一条鱼。

If you're creating it in the static HTML then just use .ready(handler) or .on("load", handler). If you're using AJAX though that's another kettle of fish.

如果你正在使用jQuery的 load()函数然后有一个回调你可以在加载内容时运行:

If you're using jQuery's load() function then there's a callback you can run when the contents been loaded:

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

如果您使用的是jQuery的 $。ajax $。获取 / $。发布函数然后成功回调:

If you're using jQuery's $.ajax or $.get/$.post functions then there's a success callback in that:

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

如果您只是创建元素并将其附加如下:

If you're just creating the element and appending it like this:

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

然后你可以这样做:

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

但这没关系 - 因为它是同步的(这意味着下一行代码赢了' t运行,直到它将元素添加到DOM中... - 除非你正在加载图像等等,所以你可以这样做:

But this won't matter - because it's synchronous (which means that the next line of code won't run until it's added the element to the DOM anyway... - unless you're loading images and such) so you can just do:

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

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

But acctually, saying THAT you could just do this:

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