将变量从数据属性传递到 onclick 函数

passing variable from data-attribute to onclick function

我有一个包含 table 条记录的页面

每一行上都有按钮我想添加一个 onclick 事件,这样它就会触发一个弹出消息,如果他们没问题,页面就会转移到另一个页面,传递在数据属性中找到的值,但我无法让它工作

Jquery 看起来像这样:

            var aFeatures = document.querySelectorAll(".sweet-roll");
        for (var i = 0; i < aFeatures.length; i++) {
                   aFeatures[i].onclick = function() {
                       swal({
                           title: "Rollback To Selected Version?",
                           text: "Are you sure you want to rollback to the selected version?",
                           type: "warning",
                           showCancelButton: true,
                           confirmButtonClass:  'btn-danger',
                           confirmButtonText:  'Yes, Rollback',
                           closeOnConfirm: false,
                           //closeOnCancel: false
                       },
                       function(){
                           window.location.href="/cms/rollback.aspx?id="+$(this).data('uuid');
                       });
                   };
               }
           };

这样每个带有 class 'sweet-roll' 的按钮都会获得 onclick 事件。

每个 html 行如下所示:

<a class="btn btn-app sweet-roll" data-uuid="97aaa88c-ac9f-11e4-807b-0026b9ba6b95"><i class="fa fa-reply-all"></i>Rollback</a>

但是它一直说该值未定义,好像找不到 data-uuid 值?

您的 this 引用的是 SweetAlert 调用方,而不是您的元素。你需要做的是将它保存在一些变量中,比方说 _this

    var aFeatures = document.querySelectorAll(".sweet-roll");

    for (var i = 0; i < aFeatures.length; i++) {
               aFeatures[i].onclick = function() {
                   var _this = this

                   swal({
                       title: "Rollback To Selected Version?",
                       text: "Are you sure you want to rollback to the selected version?",
                       type: "warning",
                       showCancelButton: true,
                       confirmButtonClass:  'btn-danger',
                       confirmButtonText:  'Yes, Rollback',
                       closeOnConfirm: false,
                       //closeOnCancel: false
                   },
                   function(){
                       window.location.href="/cms/rollback.aspx?id="+$(_this).data('uuid');
                   });
               };
           }
       };