当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - JQuery - Appended Links don't work

问题描述:

I have created a dynamic list picker script using Jquery 1.3 and PHP that sends a JSON AJAX request and returns a list of items to choose from. The AJAX call works perfectly returning an array of items that I use Jquery to append them as an unordered list to an empty container DIV. That portion of the process works as expected.

The problem comes from the fact that from that list of items, I'm drawing them as links whose clicks are handled by a rel attribute. Here's an example:

<a rel="itemPick" id="5|2" href="#">This is the link</a>

The JQUERY handler looks like:

$('a[rel=itemPick]').click(function () {

code here...

});

These links and click handlers work fine when the page loads, but when they are appended to the container DIV, the click event does not get picked up. I don't want to have to refresh the entire HTML page again, so is there something I need to do in addition to append() to get JQUERY to recognize the newly added links?

网友答案:

When you use the jQuery.click method, it's looking for all of the "a" elements that currently exist on the page. Then, when you add a new "a" element, it has no knowledge of that click event handler.

So, there's a new event model in jQuery that allows you to bind functions to all current and future elements called Live Events. You can use Live Events the same way that you use normal event binding, but they will work for all future elements specified. So, you can simply switch your binding logic to:

$('a[rel=itemPick]').live('click', function () {
    //code here...
})
网友答案:
$('a[rel=itemPick]').live("click", function (){ code here... });
网友答案:

Do you bind the event after adding the links?

分享给朋友:
您可能感兴趣的文章:
随机阅读: