Event doesn't get added in a for-loop

前端 未结 3 424
清酒与你
清酒与你 2020-12-22 10:38

This is the html. If a link is clicked I want to replace the span-element in front of it with some text.

that1

3条回答
  •  情深已故
    2020-12-22 11:15

    Don't create functions in a loop. With jQuery, there's no need for an explicit loop at all.

    $(function()
    {
        $('span[id^=sp]').each(function(n)
        {
            $('#update' + n).click(function(e)
            {
                $('#sp' + n).replaceWith(this);
                return false;
            });
        });
    });
    

    Demo: http://jsfiddle.net/mattball/4TVMa/


    You can do way better than that, though:

    $(function()
    {
        $('p > a[id^=update]').live('click', function(e)
        {
            $(this).prev().replaceWith(this);
            return false;
        });
    });
    

    Demo: http://jsfiddle.net/mattball/xySGW/

提交回复
热议问题