0

Script:

$(document).ready(function(){
    $.ajax({   
        type    : "POST",
        url     : "list_controller.php",
        data    : "a=get&list_id=my_list",
        success : function(data){
            $('#list_container').innerHTML = data;
        }
    });                     
});

HTML:

<div id="list_container"></div>

The data returned from the server contains a HTML with some clickable links which should trigger another jQuery function and reload #list_container DIV again :

<a href="#" value="a=edit&list_id=my_list&user=artur&id=110" id="adminlink">
    <img src="images/edit_user.png" />
</a>

I want these links to call other AJAX functions, f.ex:

$(document).ready(function(){
    $('#adminlink').click(function () {
        var val = $(this).attr("value");
        $.ajax({       
            type    : "POST",
            url     : "list_controller.php",
            data    : val,
            success : function(data){
                $('#list_container').innerHTML = data;
            }
        });
    });
    return false;
 });

The problem is that I'm not able to access the #adminlink anchor element that triggers the click function.

Everything else is working flawlessly, but any of the elements of the innerHTML dynamic data can't be accessed anymore.

1
  • $('body').on("click", "#adminlink", function(event){ //dostuff }); Commented Feb 26, 2013 at 17:47

1 Answer 1

5

Because you're overwriting the contents of #list_container, the #adminlink on which you registered the handler is no longer the one on the page.

The simplest solution is event delegation, which relies on event bubbling:

$('#list_container').on('click', '#adminlink', function() { 
    ...
});

i.e. it's actually the static #list_container element that receives the click event, but jQuery then checks whether it was an element with ID adminlink that was actually clicked before invoking the required handler.

Always try to use the "closest" static ancestor element that you can when using event delegation. In this case this would appear to be #list_container. In the worst case you would end up using document but then the event has to bubble all the way up through the DOM before it can be processed.

Sign up to request clarification or add additional context in comments.

2 Comments

With your latest edit now my answer looks like a complete duplicate. It took you long enough to use #list_container :)
@Alexander oh yeah - I hadn't noticed (honest) that you had used #list_container instead of document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.