事件处理程序在Ajax更新后没有连接,新的dom元素(Internet Explorer)


Event handler not wired after Ajax Update, new dom element (Internet Explorer)

问题:新插入的Dom元素没有正确连接,函数deletepost没有触发。这只发生在IE和新元素只添加到DOM。

$(function(){
        $('#postentry').submit(function() {
          var tyu = $('#tittle_ent').val();
          if(tyu.length <= 2)
            {alert('Enter More Text!'); return false;}else
            {
                $.ajax({
                    type:'post',
                    url: '/posts_in.php',
                    dataType: "json",
                    data: $("#postentry").serialize(),
                    success:function(data){
                        var tittle = data[0];
                        var id= data[1];                        
                        $('<div></div>').attr('id','post'+id).addClass('boxee').html(tittle).prependTo('#boxer');                        
                        $('<img src="img/page-text-delete-icon.png" name="'+id+'">').attr({id:'postchk'+id,onclick: 'deletepost(this.name);'}).appendTo('#post'+id);                        
                        $('#tittle_ent').val('').focus();
                    }
                });
                return false;
            }
        });
    });

使用jquery live

$(function(){
        $("#boxer img").live("click", function(){
          deletepost($(this).attr("name"));
        });
        $('#postentry').submit(function() {
          var tyu = $('#tittle_ent').val();
          if(tyu.length <= 2)
            {alert('Enter More Text!'); return false;}else
            {
                $.ajax({
                    type:'post',
                    url: '/posts_in.php',
                    dataType: "json",
                    data: $("#postentry").serialize(),
                    success:function(data){
                        var tittle = data[0];
                        var id= data[1];                        
                        $('<div></div>').attr('id','post'+id).addClass('boxee').html(tittle).prependTo('#boxer');                        
                        $('<img src="img/page-text-delete-icon.png" name="'+id+'">').attr({id:'postchk'+id,onclick: 'deletepost(this.name);'}).appendTo('#post'+id);                        
                        $('#tittle_ent').val('').focus();
                    }
                });
                return false;
            }
        });
    });

'onclick'已经过时了,尤其是在使用jquery的时候。试试这个变体:

$('<img src="img/page-text-delete-icon.png" name="'+id+'">')
    .attr('id', 'postchk'+id)
    .click(function () { deletepost(this.name); })   /// use .click() instead.
    .appendTo('#post'+id);                        

是的,你必须使用jQuery live()函数,更详细的例子可以在这里找到http://developerfaq.wordpress.com/2011/07/28/fire-event-on-dynamically-generated-dom-element-with-jquery/