Access Elements After Append

可紊 提交于 2019-12-23 15:27:42

问题


I need to access DOM elements after JQuery append. Let's say I have this:

<ul id="items">
    <li class="item">one</li>
    <li class="item">two</li>
</ul>

Then is Javascript:

var addItems = function(html) {
    $('#items').append(html);
    //How do I access the new items here?
}

Let's say that html is:

<li class="item">three</li>
<li class="item">four</li>

I need to do something to the two new items. This something includes binding events to them. So I cannot simply use $('.item') because that will add double events to the existing items. Once the new items are part of the DOM, there is nothing about them that distinguishes them from the existing items.

What's the best way to do this?


回答1:


Make a jQuery collection of the html before appending it:

var addItems = function(html) {
    var $items = $(html);
    $('#items').append($items);
    $items.foo();
}



回答2:


Here's a working example: http://jsfiddle.net/hunter/7UTA2/

var addItems = function(html) {
    var $html = $(html);
    $('#items').append($html);
    $html.text("test");
}

This showcases that you still can manipulate the text (or whatever attribute) of the items since you still have a reference to the collection.



来源:https://stackoverflow.com/questions/5937019/access-elements-after-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!