将变量从data-attribute传递给onclick函数

时间:2015-02-04 19:47:47

标签: javascript jquery html custom-data-attribute

我有一个页面,其中包含许多记录的表格

每一行都有按钮我要添加一个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');
                       });
                   };
               }
           };

所以每个带有'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值一样?

1 个答案:

答案 0 :(得分:0)

您的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');
                   });
               };
           }
       };