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

发布于 2024-11-16 10:14:54 字数 211 浏览 3 评论 0原文

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

例子:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

梦中楼上月下 2024-11-23 10:14:54

您如何创建该元素?

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

那么您可以这样做:

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

但是这个没关系 - 因为它是同步(这意味着下一行代码在将元素添加到 DOM 之前不会运行... - 除非您正在加载图像等),所以您可以这样做:

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

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

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

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.

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

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

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:

$('<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'});
对你再特殊 2024-11-23 10:14:54

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

因此,如果您有一个

    并且您在 $(document).ready() 中动态创建新的

  • 项> 您可以将选择器连接到事件处理程序,以便为该事件连接所有
  • 元素。

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

希望这有帮助。

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.

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.

Here's a jsFiddle sample that demos live.

Hope this helps.

温柔女人霸气范 2024-11-23 10:14:54

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

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.

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
    });
时光匆匆的小流年 2024-11-23 10:14:54

创建一个元素没有多大意义,除非它被插入到页面中。我认为这就是您所说的“就绪”功能的意思。

onLoad 事件仅限于某些元素,并且 divp 元素不支持。你必须选择:

你可以使用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

第二种也是更惯用的方法是在目标元素上添加一个突变观察器,并在目标发生突变时检查该元素是否是插入元素之一,即新元素是添加:

let el = document.createElement("div");
el.innerHTML = "New Div";

const targetNode = document.querySelector("body");

const observerOptions = {
  childList: true,
  attributes: true,
  subtree: false
};

function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    mutation.addedNodes.forEach((node) => {
      const isAdded = node.isEqualNode(el);
      console.log(isAdded);
    });
  });
}

const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);

document.body.appendChild(el);

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

还有两种选择,为 DOMNodeInserted添加事件监听器DOMNodeInsertedIntoDocument 事件,但由于 MutationEvent 已弃用,因此最好避免它们。

https://developer.mozilla.org/en-US/docs/ Web/API/MutationEvent

Creating an element does not mean much, unless it is inserted into the page. I think that is what you mean by ready function.

The onLoad event is limited to certain elements only, and is not supported for div or p elements. You have to options:

You can use setInterval function to check the existence of the element. Once the element is found, you can clear the interval:

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

The second and the more idiomatic way is adding a mutation observer on the target element, and checking if the element is one of the elements inserted elements whenever target is mutated, i.e new element is added:

let el = document.createElement("div");
el.innerHTML = "New Div";

const targetNode = document.querySelector("body");

const observerOptions = {
  childList: true,
  attributes: true,
  subtree: false
};

function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    mutation.addedNodes.forEach((node) => {
      const isAdded = node.isEqualNode(el);
      console.log(isAdded);
    });
  });
}

const observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);

document.body.appendChild(el);

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

There are two more alternatives, adding event listener for DOMNodeInserted or DOMNodeInsertedIntoDocument events but since MutationEvent is deprecated, it is best to avoid them.

https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent

半窗疏影 2024-11-23 10:14:54

你可以试试这个代码

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

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>

做个少女永远怀春 2024-11-23 10:14:54

创建元素后最好检查 .live() ,

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

然后添加一个新元素:

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

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

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

And then later add a new element:

$('body').append('<div class="clickme">Another target</div>');
倾`听者〃 2024-11-23 10:14:54
$("<div id=\"elem\"></div>").appendTo("#parent").each(function(){

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

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

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

});
如果没有你 2024-11-23 10:14:54

旧线程,但就我而言,我遇到了一个大追加树的情况,可以这么说,我想进行一些内嵌初始化,并执行了以下操作:

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

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
  })
...    
)
埖埖迣鎅 2024-11-23 10:14:54

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文