2017-04-22 83 views
-1

jQuery代碼:jQuery數據值沒有更新。如何解決這個問題?

if($(this).attr('data-status') == 'Yes'){ 
    alert('if'); 
    $(this).attr("data-status","No"); 
} 
else{ 
    alert('else'); 
    $(this).attr("data-status","Yes"); 
} 

jQuery函數代碼:

$(".Notification").click(function(){ 
    var notification = { 
    petid: $(this).attr('data-value'), 
    status: $(this).attr('data-status') 
    } 
    var formurl = '<?php echo base_url();?>index.php/Dashboard/notification'; 
    $.ajax({ 
    method: "POST", 
    url: formurl, 
    data: notification, 
    success: function(response){ 
     if($(this).attr('data-status') == 'Yes'){ 
      alert('if'); 
      $(this).attr("data-status","No"); 
     } 
     else{ 
      alert('else'); 
      $(this).attr("data-status","Yes"); 
     } 
    } 
    }) 
}) 

HTML代碼:

<input type="checkbox" class="Notification" data-value="6" data-status="Yes" checked=""> 

我想更新的數據狀態的值,但它不能正常工作。它提醒我,否則。但沒有更新價值。

+0

BTW ...你的成功*''response'用於什麼? –

回答

1

$(this)將不會引用您的元素在成功內部,因此在點擊事件的頂部定義$(this)

change事件應該用於複選框(因爲不需要click觸發複選框更改事件)的詳細信息

$(".Notification").on("change", function() { 

    var ThisIt = $(this); 

    var notification = { 
    petid: ThisIt.attr('data-value'), 
    status: ThisIt.attr('data-status') 
    } 

    var formurl = '<?php echo base_url();?>index.php/Dashboard/notification'; 

    $.ajax({ 
    method: "POST", 
    url: formurl, 
    data: notification, 
    success: function(response){ 
     if(ThisIt.attr('data-status') == 'Yes'){ 
      alert('if'); 
      ThisIt.attr("data-status","No"); 
     } 
     else{ 
      alert('else'); 
      ThisIt.attr("data-status","Yes"); 
     } 
    } 
    }) 
}) 

你可以看看:https://stackoverflow.com/a/6394826/3385827