2015-04-03 20 views
1

我使用jquery.confirm這是我從http://myclabs.github.io/jquery.confirm/拿起變化事件的jquery.confirm功能使用上覆選框

目的: - 我想彈出不同的文本確認對話框上的檢查和取消選中的複選框。檢查複選框時,彈出一個確認框,顯示消息"Are You Sure to add the media",如果用戶單擊「是我是」,則發送相應的ajax調用以添加媒體並使檢查屬性爲true。在取消選中該複選框時,彈出確認窗口,顯示消息"Are you Sure to delete the media",同樣,如果用戶選擇「是我是」,則正在進行ajax調用以進行刪除,並將選中的屬性設置爲false。

該複選框是:

<input type="checkbox" id="media"> 

現在的問題是,雖然流得到正確去,確認框顯示在複選框的兩個檢查並取消同一文字信息。

"Are You sure to add the media". 

相反,它應該改變文本,因爲textMessage在每次檢查時改變並取消選中。這是我第一次使用確認框。

這是代碼。

var textMessage=" to add the media?"; 
    $('#media').change(function() { 
      //var checked=$(this).is(":checked"); 
      var me=this; 
      $("#media").confirm({ 
          title:"Confirmation", 
          text:"Are You Sure" + textMessage, 
          confirm: function(btn) { 
           if(textMessage === " to add the media"){ 
            $(me).prop("checked", true); 
            mediachecked=false; 
            textMessage=" to delete the media?"; 
            //Making the ajax calls for addition               
            } 
           else{ 
            $(me).prop("checked",false); 
            mediachecked=true; 
            textMessage=" to add the media?"; 
            //Making the ajax calls for deletion 
            } 
          }, 
          cancel: function(btn) { 
          }, 
          confirmButton: "Yes I am", 
          cancelButton: "No" 
          }); 
     }); 

在此先感謝您的幫助。

回答

1

好吧,我想我已經明白了。 jQuery.confirm希望您將事件附加到按鈕(或複選框,與您的情況相同)。你已經完成的方式,你應該使用手動觸發方法。反正,我能夠得到這個無需修改過多代碼的工作:

//The checkbox. Notice the data attribute that will hold the confirm text message 
<input type="checkbox" id="media" data-text="Are you sure you want to add the media?" /> 

及以下的jQuery代碼(摘要爲了簡潔)。您不應該聽取複選框的change事件,並且每次都重新附加確認事件偵聽器(這是您的代碼的問題),您應該立即將確認事件偵聽器附加到複選框,然後使用某種方法更改確認對話框文本。我已經使用data-屬性來存儲文本,jQuery.confirm自動使用它作爲提示文本。見下面的代碼:

//Notice the btn.data(...) call to change value of 'data-text'... 
$("#media").confirm({ 
    title:"Confirmation", 
    confirm: function(btn) { 
     if(!btn.is(":checked")){ 
      btn.prop("checked", true); 
      btn.data("text","Are you sure you want to delete the media?"); 
      //Making the ajax calls for addition               
     }else{ 
      btn.prop("checked",false); 
      btn.data("text","Are you sure you want to add the media?"); 
      //Making the ajax calls for deletion 
     } 
    }, 
    cancel: function(btn) {}, 
    confirmButton: "Yes I am", 
    cancelButton: "No" 
}); 
+0

非常感謝。有效。 :) – 2015-04-03 10:08:05