简体   繁体   English

将元素插入DOM后,如何对元素执行jQuery函数?

[英]How do I perform a jQuery function on an element after it has been inserted into the DOM?

Consider the following code 考虑以下代码

    $li         = $('<li></li>');
    $divHandle  = $('<div></div>');
    $divContent = $('<div></div>');
    $i          = $('<i></i>');
    $span       = $('<span></span>');
    $spanEnd    = $('<span></span>');
    $spanIndex  = $('<span></span>');
    $wrapper    = $('<div></div>');

    $divHandle.addClass('dd-handle').addClass('dd3-handle');
    $divContent.addClass('dd3-content').append($spanIndex).append($span);

    $i.attr('title','Delete this Node').addClass('icon-remove-sign');
    $spanEnd.addClass('delete-element-node').append($i);

    $li.addClass('dd-item').addClass('dd3-item');

    $divContent.append($spanEnd);

    $li.append($wrapper.append($divHandle).append($divContent));

    $('#ExhibitNodes > ol').append($li);

In this, I am appending an element $divContent to a list item which is inserted into the DOM. 在这里,我将元素$divContent附加到插入DOM的列表项中。 My question is, is there a way that is akin to passing objects by reference (like PHP or something) that will allow you to do this: 我的问题是,是否有一种类似于通过引用传递对象(如PHP或其他方式)的方法,该方法可让您执行此操作:

    $divContent.fn.applyFunction();

After that $divContent has been inserted into the DOM. 之后,将$divContent插入到DOM中。 What we need to do, is insert the element to the DOM, with a loading indicator. 我们需要做的是将元素插入到DOM中,并带有一个加载指示器。 The loading indicator will display while an AJAX procedure is called, and when the AJAX is complete and successful, it will update that element using that function. 当调用AJAX过程时,将显示加载指示器,当AJAX完成并成功执行时,它将使用该函数更新该元素。 But in order to do that, we need to insert it to the DOM first. 但是为了做到这一点,我们需要先将其插入到DOM中。

Thoughts? 有什么想法吗?

The answer was actually quite simple. 答案实际上很简单。 I did not know this, and by sheer experimentation it worked. 我不知道这一点,通过纯粹的尝试,它奏效了。

http://jsfiddle.net/z3es9/

Basically, I create an element $element - give it some properties and a class, then $.append() it to the DOM. 基本上,我创建一个元素$element给它一些属性和一个类,然后将其$.append()传递给DOM。

Clicking the button modifies the original $element and passes the changes on to the inserted/appended DOM element. 单击按钮将修改原始的$element并将更改传递到插入/附加的DOM元素上。

Wow. 哇。 Cool! 凉! Hope this helps someone! 希望这对某人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM