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 に答える