[英]Fire event only when an unchecked checkbox gets checked
我有這個 JavaScript function 我只想在未選中的框被選中並且我的 get 請求返回 true 時觸發。 發出警報時,hasCoPrimary 為真,但 if 語句從不觸發。 我認為這是因為復選框在 if 語句通過之后才注冊為“已選中”? 如何讓 function 等待復選框更改被注冊,以便我可以在 if 語句中使用它?
$('#btn-isPrimary').on('change', function (e) {
$.get('/Ingredient/CheckForCoPrimary/', { code: "@Model.Code", id: @Model.Id }, function (hasCoPrimary) {
//Only shows modal if the item being made primary already has another ingredient with the same code marked as primary
if ($(this).is(':checked') && hasCoPrimary === true) {
$("#primary-modal").modal();
}
});
});
編輯:將代碼更改為此,但仍然無法正常工作。 在進入 if 語句之前,我有一個警報告訴我 hasCoPrimary 是什么,並且它每次都是 True,因此該部分是正確的。
$('#btn-isPrimary').on('change', function (e) {
var checkbox = $('#btn-isPrimary');
$.get('/Ingredient/CheckForCoPrimary/', { code: "@Model.Code", id: @Model.Id }, function (hasCoPrimary) {
alert(hasCoPrimary);
//Only shows modal if the item being made primary already has another ingredient with the same code marked as primary
if (checkbox.is(':checked') && hasCoPrimary === true) {
$("#primary-modal").modal();
}
});
});
我也試過這個
$('#btn-isPrimary').on('change', function (e) {
var checkbox = $('#btn-isPrimary');
$.get('/Ingredient/CheckForCoPrimary/', { code: "@Model.Code", id: @Model.Id }, function (hasCoPrimary) {
alert(hasCoPrimary);
//Only shows modal if the item being made primary already has another ingredient with the same code marked as primary
if (e.currentTarget.checked && hasCoPrimary === true) {
$("#primary-modal").modal();
}
});
});
問題是$(this)
不再是復選框,一旦你進入你的$.get
回調 function - 你要么需要在你的回調 function 之前設置一個變量,或者更好,你可以使用e.currentTarget.checked
= as您正在將e
傳遞到您的更改 function 中, e.currentTarget
是已更改的復選框
$('#btn-isPrimary').on('change', function(e) {
$.get('/Ingredient/CheckForCoPrimary/', {
code: "@Model.Code",
id: @Model.Id
}, function(hasCoPrimary) {
//Only shows modal if the item being made primary already has another ingredient with the same code marked as primary
if (e.currentTarget.checked && hasCoPrimary === true) {
$("#primary-modal").modal();
}
});
});
但是,如果您只打算在復選框被選中時顯示模式,那么我會將 if 語句的選中部分移到$.get
之外,這樣您就不會進行不必要的 ajax 調用:
$('#btn-isPrimary').on('change', function(e) {
if (e.currentTarget.checked) {
$.get('/Ingredient/CheckForCoPrimary/', {
code: "@Model.Code",
id: @Model.Id
}, function(hasCoPrimary) {
//Only shows modal if the item being made primary already has another ingredient with the same code marked as primary
if (hasCoPrimary === true) {
$("#primary-modal").modal();
}
});
}
});
如果以上內容沒有進入if (hasCoPrimary === true)
,您可能需要檢查hasCoPrimary
是布爾值還是字符串 - 如果它在您的編輯中像True
一樣發出警報,您可能需要嘗試if (hasCoPrimary === 'True')
。 還要注意currentTarget
上的小 c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.