jQuery.on('click')显示Window为$(this)的值

问题描述 投票:0回答:1

我已经动态地添加了存储在jQuery的.data()缓存中的数据的内容。当动态创建内容时,还为每个div动态创建按钮(注意,每个生成的div都存储上述数据)。当我尝试单击其中一个按钮时,为按钮单击事件设置的事件侦听器表示$(this)的值是Window而不是单击的按钮。

我最终想调用这个$(this).parent().data('commentID')从父div获取存储的id值,以便弹出作为删除确认的模式可以简单地对一个以commentID结尾的URL进行AJAX调用(我已经注释掉了我想要的内容)如果$(this)正在选择正确的东西,请致电)。

这是工作示例的CodePen。请注意,您必须打开开发工具控制台才能看到$(this)生成Window而不是单击的按钮。 https://codepen.io/anon/pen/pBXaKw?editors=1010

这是HTML

<button type="button" value="Search" class="btn btn-primary" id="searchCommentBtn">Generate comments</button>

<section id="commentsSection">

</section>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

这是JS

$('#searchCommentBtn').click(() => {
  for(let i=0; i<4;i++) {
    let WFTComment = $('<div class="work-task-comment-div">'+i+'</div>').data('commentID', i);
    WFTComment.append('</br>', createBtn('myModal', 'Remove'));
    $('#commentsSection').append(WFTComment);
  }
});


var createBtn = (targetModal, btnName) => {
    let btn = $('<button type="button" class="btn btn-sm btn-dark removeCommentBtn" data-toggle="modal" data-target="#' + targetModal + '">' + btnName + '</button>');
    return btn;
}

$('#commentsSection').on('click', 'button', (e) => {
    console.log($(this));
    // let commentID =  $(this).parent().data('commentID');
    // $('#confirmDelete').on('click', () => {
    //   $.ajax({
    //     method: 'POST',
    //     url: 'api/CommentsAPI/' + commentId
    //   })
    // })
});
jquery event-handling this event-delegation
1个回答
0
投票

解决方法是简单地从事件侦听器中删除箭头函数并使用传统的函数调用。

$('#commentsSection').on('click', 'button', function(e) {
    console.log($(this));
    // let commentID =  $(this).parent().data('commentID');
    // $('#confirmDelete').on('click', () => {
    //   $.ajax({
    //     method: 'POST',
    //     url: 'api/CommentsAPI/' + commentId
    //   })
    // })
});
© www.soinside.com 2019 - 2024. All rights reserved.