3 回答
TA貢獻1900條經驗 獲得超5個贊
最后,通過混合來自 Rory 的鏈接和組織代碼的想法。我已經找到了解決我的問題的方法。所以,如果有人遇到類似的問題,這里是我的解決方案。
$(function(){
var lastSel;
$('#buildingSelect').on('focusin', function(){
lastSel = $("#buildingSelect option:selected");
}).on('change', function(){
if(!checkDirtyStatus()) {
lastSel.prop("selected", true);
return;
}else{
//made ajax call
//$.ajax({})
}
});
});
function checkDirtyStatus(){
let dirtyStatus = getDirtyStatus();
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
return true;
}
TA貢獻1836條經驗 獲得超13個贊
讓我們看看你的功能:
function checkDirtyStatus(){
dirtyStatus = true; // I assume this is only for testing
if(dirtyStatus === true){ // This can be simplified.
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
確認返回一個布爾值,它要么是真要么是假,所以你可以像這樣簡化你的函數:
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
// Notice that you do not return anything here. That means that
// the function will return undefined.
}
您的其他功能可以這樣簡化:
$('#buildingSelect').on('change', function(){
if(!checkDirtyStatus()){
// Here you probably want to set the value of the select-element to the
// last valid state. I don't know if you have saved it somewhere.
return;
}
//make ajax call
});
TA貢獻1775條經驗 獲得超8個贊
我玩過你的 codepen,你的選擇器有一些錯誤。當我對您的解釋感到困惑時,我將嘗試解釋您可以更新的內容以及如何在您的代碼中使用它,我希望這是您解決問題所需要的。
首先,我會將您的 js 更改為:
var lastSel = $("#buildingSelect").val();
$("#buildingSelect").on("change", function(){
if ($(this).val()==="2") {
$(this).val(lastSel);
return false;
}
});
在 jquery 中獲取選擇框值的正確方法是使用.val(). 在您的情況下,您選擇了整個選定的選項元素。我將此值存儲在lastSel變量中。然后在更改函數中,選擇列表的新值是$(this).val()。我檢查這個值,如果它等于 2,我將它恢復為存儲在 lastSel 變量中的值$(this).val(lastSel)。請記住,選擇列表的值始終是字符串,如果要檢查數字,必須首先將其轉換為數值,例如使用 parseInt。
如果您想使用 checkDirtyStatus 進行檢查,那么您應該只在更改中調用此函數并將 lastSel 和 newSel 作為參數傳遞,如下所示:
$("#buildingSelect").on("change", function(){
checkDirtyStatus(lastSel, $(this).val());
});
然后,您可以將更改函數中的邏輯轉移到 checkDirtyStatus 函數中,并在那里進行檢查。在這種情況下,如果您希望恢復選擇值而不是$(this).val(lastSel)您將執行$("#buildingSelect").val(lastSel).
我希望這有幫助。
添加回答
舉報
