Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Ajax - selector don't work

Tags:

jquery

ajax

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 PUBLIC "-//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. :)

like image 472
A-OK Avatar asked Mar 10 '26 05:03

A-OK


1 Answers

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!");
    });
like image 162
Kon Avatar answered Mar 12 '26 21:03

Kon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!