开发者

JQuery will not recognize a created element

I am having trouble getting jquery to recognize an element that is created from a form change. I have it set up so when i select something a link is created with but when I add a click function to the created item nothing will happen. How can i make this work?

$(function() {

var i = $('#nav li').size() + 1;

$('a#add').click(function() {
    $('<li>' + i + '<a href="#" id="add">yes</a></li>').appendTo('ul');
    i++;
});

$('a#remove').click(function() {
    $('li:last').remove();
    i--;
});


});

html code

<ul id="nav">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<a href="#" id="add"开发者_JAVA百科>Add List Item</a><br/>
<a href="#" id="remove">Remove LI</a>


You need to use live to bind event handlers for dynamically created elements. Your current code will create multiple html elements with same id which is not valid. You can use class names instead to identify the src elements.

Try this:

$(function() {
    var i = $('#nav li').size() + 1;
    $('a.add').live("click", function() {
        $('<li>' + i + '<a href="#" class="add">yes</a></li>').appendTo('ul');
        i++;
    });

    $('a.remove').live("click", function() {
        $('li:last').remove();
        i--;
    });
});

html code

<ul id="nav">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
</ul>
<a href="#" class="add">Add List Item</a><br/>
<a href="#" class="remove">Remove LI</a>


Change your jquery to this:

$(function() {
    var i = $('#nav li').size() + 1;

    $('a#add').live('click', function() {
        $('<li>' + i + '<a href="#" id="add">yes</a></li>').appendTo('ul');
        i++;
    });

    $('a#remove').live('click', function() {
        $('li:last').remove();
        i--;
    });
});


You can't use the .click here. .click is just .bind with the mouse event action. You have to use the .live


To attach an event to a selector and all other created by jQuery, you must use the .live() function instead of the .click() shorthand.

You code to attach the 'click' event to you 'a#add' link would look like this :

$('a#add').live('click', function() {
    $('<li>' + i + '<a href="#" id="add">yes</a></li>').appendTo('ul');
    i++;
});


id="add" is only allowed on one element per page. If you use it more than once, bizarre things can happen. Change your code to:

$(function() {
    var i = $('#nav li').size() + 1;

    $('a#add').click(function() {
        $('<li>' + i + '<a href="#" class="add">yes</a></li>').appendTo('ul');
        i++;
    });

    $('ul a.add').live('click', function() {
        // handle any link with class "add" that was dynamically added to the ul
    });

    $('a#remove').live('click', function() {
        $('li:last').remove();
        i--;
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜