簡體   English   中英

將變量從數據屬性傳遞給onclick函數

[英]passing variable from data-attribute to onclick function

我有一個頁面,其中包含許多記錄的表

每行上都有一個按鈕,我想添加一個onclick事件,以便觸發一個彈出消息,如果他們確定,該頁面將轉移到另一個頁面,並傳遞data屬性中找到的值,但我無法使其正常工作

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>

但是它一直在說該值是不確定的,好像找不到數據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');
                   });
               };
           }
       };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM