开发者

Access Elements After Append

开发者 https://www.devze.com 2023-03-04 03:45 出处:网络
I need to access DOM elements after JQuery append.Let\'s say I have this: <ul id=\"items\"> <li class=\"item\">one</li>

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?


Make a jQuery collection of the html before appending it:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消