简体   繁体   中英

click event not firing on newly created list item

I have two lists and when you click on the second list the first list removes the first item and add to the second list but when I click on the newly created list item it doesn't fire why is that. jsFiddle demo

$('#SearchList li a').bind("click", function () {
    var $this = $(this).unwrap('<a href="#"></a>').remove().text();

    var $that = $('#Search li:first').remove().text();

    $('<li>' + $this + '</li>').insertBefore('#Search li:first')

    $('#SearchList').append('<li><a href="#">' + $that + '</a></li>');
});

<ul id="Search">
    <li>Electronics</li>
    <li>Image</li>
</ul>

<ul id="SearchList">                        
    <li><a href="#">Interests</a></li>
    <li><a href="#">Entertainment</a></li>
    <li><a href="#">Clothing</a></li>
    <li><a href="#">Pharmacy</a></li>
    <li><a href="#">Home & Garden</a></li>
</ul>

.bind() only affects elements already in the DOM, you want to use .delegate() or .on() (if you are using jQuery 1.7+):

$('#SearchList').on("click", " li a", function () {
    var $this = $(this).unwrap('<a href="#"></a>').remove().text();

    var $that = $('#Search li:first').remove().text();

    $('<li>' + $this + '</li>').insertBefore('#Search li:first')

    $('#SearchList').append('<li><a href="#">' + $that + '</a></li>');
});

Note: .live() has been depreciated as of jQuery 1.7, so it's a good idea to either use .on() or .delegate() .

Here is a jsfiddle of the above solution (using jQuery 1.7): http://jsfiddle.net/jasper/pgwdv/

Some documentation links:

您应该尝试使用.live而不是.bind。

You can use the live function to keep click (and other) handlers active for dynamically added content.

Instead of

$('#SearchList li a').bind("click", function () {

Use

$('#SearchList li a').live("click", function () {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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