1

我正在做我自己的项目,我对一个新的动态生成节点有一点问题,它没有被点击这里是代码示例:

HTML:

<ul id="container-comments">
    <li>
        <a href="#" class="comment-avatar" title="imax9">
           <img src="images/avatar.png" alt="imax9" />
        </a>
        <div class="content-box comment__body">
           <div class="comment__header">
              <a href="/user/imax9" class="comment__username">imax9</a>
              <div class="comment__meta">
                <span>8 hours ago</span>
              </div>
              <div class="edit" title="Edit">
                edit
              </div>
           </div>

          <div class="comment__content">
             <p>wonderful! Good luck with sales!</p>
          </div>
        <div class="comment__inline-edit"></div>

     </div>
   </li>

  </ul>

jQuery:

$('#comment-submit input[type=submit]').click(function (e) {
        e.preventDefault();
        updateComments(params); //this function updates the ul by adding
                                //new li contains the same html structure 
});

//it doesn't work for the new generated one
$('.edit').on('click', function () {
        var index = $('.edit').index(this);
        var commentEdit = $('.comment__content p').eq(index).text();
        $('.comment__content').eq(index).html('<textarea style="width: 500px; height: 50px; padding: 0px; resize: none;">' + commentEdit + '</textarea>');
        //then it supposed when i press enter key the edit is done
});

非常感谢

4

3 回答 3

2

您没有使用.on()正确的方式来处理动态元素。

尝试这个。

$('#container-comments').on('click', '.edit', function () {
        var index = $('.edit').index(this);
        var commentEdit = $('.comment__content p').eq(index).text();
        $('.comment__content').eq(index).html('<textarea style="width: 500px; height: 50px; padding: 0px; resize: none;">' + commentEdit + '</textarea>');
        //then it supposed when i press enter key the edit is done
});

结构就像

$('static selector').on('event', 'dynamic selector', function(){...});

否则它将像正常一样工作click

于 2013-05-26T15:23:31.037 回答
1

尝试:

$(document).ready(function(){
    $(document).on('click','.edit',function(){
       // your function
    });
});
于 2013-05-26T15:22:17.750 回答
0

使用委托:

$('#container-comments').undelegate('.edit', 'click').delegate('.edit', 'click', function() {
     ...
     ...
}
于 2013-05-26T15:24:58.377 回答