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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6386128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:30:30  来源:igfitidea点击:

How can I call a function after an element has been created in jquery?

javascriptjqueryloaded

提问by Dennis Martinez

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

回答by Thomas Clayson

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(handler).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 $.ajaxor $.get/$.postfunctions 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'});

回答by David Hoerster

You may want to look into jQuery liveevents. 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.

因此,如果您有一个<ul>并且动态创建新<li>项目,则可以在您$(document).ready()的选择器<li>中将选择器连接到事件处理程序,以便为该事件连接所有元素。

Here's a jsFiddlesample that demos live.

这是演示的jsFiddle示例live

Hope this helps.

希望这可以帮助。

回答by K6t

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

回答by MEAbid

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>

回答by Dimitar Nikovski

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

回答by SnnSnn

You can use setIntervalfunction to check the existence of an element. Once the function runs, you can clear the interval:

您可以使用setInterval函数来检查元素是否存在。函数运行后,您可以清除间隔:

var CONTROL_INTERVAL = setInterval(function(){
    // Check if element exist
    if($('#some-element').length > 0){
        // ...
        // Since element is created, no need to check anymore
        clearInterval(CONTROL_INTERVAL);
    }
}, 100); // check for every 100ms

回答by Piotr

old thread, but in my case i had a situation with a big append-tree, and i wanted to do some initialization in-line so to speak, and did the following:

旧线程,但在我的情况下,我遇到了一个大附加树的情况,我想在线进行一些初始化,并执行以下操作:

$("<div>").append(
  ...
  $("<div>").foo(...).bar(...).etc(...).each(function(){
    // init code to run after chain of init functions called
  })
...    
)

回答by Tomgrohl

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

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

});

回答by Gerry

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

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