如何在jquery中创建元素后调用函数? [英] How can I call a function after an element has been created in jquery?

查看:89
本文介绍了如何在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'});

这篇关于如何在jquery中创建元素后调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆