开发者

jQuery/Ajax - selector don't work

When I use jQuery.ajax() to load HTML content from some PHP into an element on the page, jQuery selectors don't work on elements in that loaded HTML.

Is this a common problem or do I have to put together an example?

<!DOCTYPE html PUBLI开发者_开发百科C "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="../jquery.js" type="text/javascript"></script> 
</head>
<body>
    <div id="htmlcontent">
        <a href="#">Blah</a><br />
        <a href="#">Bleh</a><br />
    </div>
    <div id="replacecontent">
        <br /><a href="#">Replace content</a>
    </div>
    <script type="text/javascript">
        $("#htmlcontent a").click(function() {
            alert("Clicked on a link!");
        });
        $("#replacecontent a").click(function() {
            $("#htmlcontent").html('<a href="#">This doesn't alert(). Why?</a>');
        });         
    </script>
</body>

Ok, that wasn't too hard. :)


I'm sure your selectors are just fine. It's probably the event handlers that aren't bound right. are you using .bind() or .click()? A common problem is that you can't use those standard events to bind to from elements that don't exist yet on the page. You may want to look into .live(), which attaches a handler to the event for all elements which match the current selector, now and in the future.

So try this:

    $("#htmlcontent a").live('click', function() {
        alert("Clicked on a link!");
    });


Selectors don't work after you have modified your DOM, because the elements they were attached to will be manipulated or removed. If you want to bypass this, you would have to use $.live() or $.delegate().

This is the explanation for the .live() event attachment:

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.


The elements you're trying to select are not present in the DOM at the time the click() events are bound.

Have a look at jQuery.delegate(): Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

    $("#replacecontent").delegate("a", "click", function() {
        $("#htmlcontent").html('<a href="#">This will work now alert(). Why?</a>');
    }); 

I prefer .delegate() over .live() since it's more efficient, giving us an easy way to specify a context for the selector. With .live(), every single click on the entire document has to be compared to the specified selector, with .delegate() just elements in the $("#replacecontent") container.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜