0

脚本

$(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>

从服务器返回的dataHTML 包含一些可点击的链接,这些链接应该会触发另一个 jQuery 函数并#list_container再次重新加载 DIV:

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

我希望这些链接调用其他 AJAX 函数 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;
 });

问题是我无法访问#adminlink触发点击功能的锚元素。

其他一切都完美无缺,但不能再访问innerHTML动态的任何元素。data

4

1 回答 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.

于 2013-02-26T17:46:28.707 回答