我有這個 JavaScript 函式,我只想在未選中的框被選中并且我的 get 請求回傳 true 時觸發。警報時,hasCoPrimary 為真,但 if 陳述句永遠不會觸發。我認為這是因為在 if 陳述句通過之前復選框不會注冊為“已選中”?如何讓函式等待復選框更改被注冊,以便我可以在 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();
}
});
});
uj5u.com熱心網友回復:
問題是,$(this)一旦您進入回呼函式,就不再是復選框$.get- 您需要在回呼函式之前設定一個變數,或者更好的是,您可以e.currentTarget.checked在傳遞e給更改函式時使用 =,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'). 還要注意小ccurrentTarget
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459875.html
