为什么 $(this).data('id') 在对话框中使用时不起作用?

Why is $(this).data('id') not working when using in a dialog?

我最初有这个功能可以在单击 delete-item 按钮时删除一个项目:

$( document ).on( "click", ".delete-item", function() {

                    console.log("Removing "+$(this).data('id'));
                    var id=$(this).data('id');
                    var parent=$(this).parent().parent().parent();      
                    parent.remove();
                    $(".subitem-row"+id).remove();
                    applyCartChanges();

});

它工作正常。但是当我尝试做一个对话框(使用 OnsenUI 和 PhoneGap)在删除之前首先确认它,就像这样:

$( document ).on( "click", ".delete-item", function() {

        ons.notification.confirm({
          message: getTrans('Remove from cart?','remove_from_cart') ,     
          title: dialog_title_default ,
          buttonLabels: [ getTrans('Yes','yes') ,  getTrans('No','no') ],
          animation: 'default', // or 'none'
          primaryButtonIndex: 1,
          cancelable: true,
          callback: function(index) {

               if (index==0){                         

                    console.log("Removing "+$(this).data('id'));
                    var id=$(this).data('id');
                    var parent=$(this).parent().parent().parent();      
                    parent.remove();
                    $(".subitem-row"+id).remove();
                    applyCartChanges();

               }
          }
        });

});

然后它突然不再工作了:(在控制台中,它说 undefined 代表 $(this).data('id')。知道为什么吗?

这是因为对 this 的引用不是作为对话框中单击的元素获得的。因此,将您的代码重写为

$( document ).on( "click", ".delete-item", function() {
        var _this = this;
        ons.notification.confirm({
          message: getTrans('Remove from cart?','remove_from_cart') ,     
          title: dialog_title_default ,
          buttonLabels: [ getTrans('Yes','yes') ,  getTrans('No','no') ],
          animation: 'default', // or 'none'
          primaryButtonIndex: 1,
          cancelable: true,
          callback: function(index) {

               if (index==0){                         

                    console.log("Removing "+$(_this).data('id'));
                    var id=$(_this).data('id');
                    var parent=$(_this).parent().parent().parent();      
                    parent.remove();
                    $(".subitem-row"+id).remove();
                    applyCartChanges();

               }
          }
        });

});

请注意,我在新变量 _this 中引用了 this,因此可以在对话框中访问它。