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

时间:2023-01-20 21:21:13

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

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

Example:

例:

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

7 个解决方案

#1


36  

How are you creating the element?

你是如何创建元素的?

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.

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

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

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

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

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

如果你正在使用jQuery的$ .ajax或$ .get / $。post函数,那么有一个成功的回调:

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

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

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

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

Then you can do this instead:

然后你可以这样做:

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

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:

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

$('<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'});

#2


7  

You may want to look into jQuery live events. You attach an event handler to a selector that either matches now or after additional elements are created in your DOM.

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

So if you have a <ul> and you dynamically create new <li> items, in your $(document).ready() you can wire up a selector to an event handler so that all of your <li> elements will be wired for that event.

因此,如果您有

    并动态创建新的
  • 项目,则可以在$(document).ready()中将选择器连接到事件处理程序,以便将所有
  • 项目,则可以在$(文件)。就绪()中将选择器连接到事件处理程序,以便将所有
  • 元素连接起来对于那个事件。

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

Here's a jsFiddle sample that demos live.

这是一个演示实时的jsFiddle示例。

Hope this helps.

希望这可以帮助。

#3


1  

you can try this code

你可以试试这段代码

$('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>

#4


1  

Sometimes this is needed for a DOM element created/loaded outside of your own script, either by a different js library or an event outside of your direct control.

有时,对于在您自己的脚本之外创建/加载的DOM元素,需要使用不同的js库或直接控制之外的事件。

For such scenarios, I always set an interval which checks periodically whether the target element exists and if this is true, the interval deletes itself and runs a callback function.

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

For this, I have a predefined function which I reuse:

为此,我有一个我重复使用的预定义函数:

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
    });

#5


1  

check out .live() its best after the element created,,

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

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

And then later add a new element:

然后添加一个新元素:

$('body').append('<div class="clickme">Another target</div>');

#6


0  

$("<div id=\"elem\"></div>").appendTo("#parent").each(function(){

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

});

#7


-1  

The most straight-forward is to directly invoke the callback after creating the element :)

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

#1


36  

How are you creating the element?

你是如何创建元素的?

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.

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

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

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

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

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

如果你正在使用jQuery的$ .ajax或$ .get / $。post函数,那么有一个成功的回调:

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

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

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

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

Then you can do this instead:

然后你可以这样做:

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

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:

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

$('<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'});

#2


7  

You may want to look into jQuery live events. You attach an event handler to a selector that either matches now or after additional elements are created in your DOM.

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

So if you have a <ul> and you dynamically create new <li> items, in your $(document).ready() you can wire up a selector to an event handler so that all of your <li> elements will be wired for that event.

因此,如果您有

    并动态创建新的
  • 项目,则可以在$(document).ready()中将选择器连接到事件处理程序,以便将所有
  • 项目,则可以在$(文件)。就绪()中将选择器连接到事件处理程序,以便将所有
  • 元素连接起来对于那个事件。

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

Here's a jsFiddle sample that demos live.

这是一个演示实时的jsFiddle示例。

Hope this helps.

希望这可以帮助。

#3


1  

you can try this code

你可以试试这段代码

$('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>

#4


1  

Sometimes this is needed for a DOM element created/loaded outside of your own script, either by a different js library or an event outside of your direct control.

有时,对于在您自己的脚本之外创建/加载的DOM元素,需要使用不同的js库或直接控制之外的事件。

For such scenarios, I always set an interval which checks periodically whether the target element exists and if this is true, the interval deletes itself and runs a callback function.

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

For this, I have a predefined function which I reuse:

为此,我有一个我重复使用的预定义函数:

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
    });

#5


1  

check out .live() its best after the element created,,

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

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

And then later add a new element:

然后添加一个新元素:

$('body').append('<div class="clickme">Another target</div>');

#6


0  

$("<div id=\"elem\"></div>").appendTo("#parent").each(function(){

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

});

#7


-1  

The most straight-forward is to directly invoke the callback after creating the element :)

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