3 回答

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
最后,通過混合來自 Rory 的鏈接和組織代碼的想法。我已經(jīng)找到了解決我的問題的方法。所以,如果有人遇到類似的問題,這里是我的解決方案。
$(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貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
讓我們看看你的功能:
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;
}
}
}
確認(rèn)返回一個(gè)布爾值,它要么是真要么是假,所以你可以像這樣簡化你的函數(shù):
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貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
我玩過你的 codepen,你的選擇器有一些錯(cuò)誤。當(dāng)我對您的解釋感到困惑時(shí),我將嘗試解釋您可以更新的內(nèi)容以及如何在您的代碼中使用它,我希望這是您解決問題所需要的。
首先,我會(huì)將您的 js 更改為:
var lastSel = $("#buildingSelect").val();
$("#buildingSelect").on("change", function(){
if ($(this).val()==="2") {
$(this).val(lastSel);
return false;
}
});
在 jquery 中獲取選擇框值的正確方法是使用.val(). 在您的情況下,您選擇了整個(gè)選定的選項(xiàng)元素。我將此值存儲(chǔ)在lastSel變量中。然后在更改函數(shù)中,選擇列表的新值是$(this).val()。我檢查這個(gè)值,如果它等于 2,我將它恢復(fù)為存儲(chǔ)在 lastSel 變量中的值$(this).val(lastSel)。請記住,選擇列表的值始終是字符串,如果要檢查數(shù)字,必須首先將其轉(zhuǎn)換為數(shù)值,例如使用 parseInt。
如果您想使用 checkDirtyStatus 進(jìn)行檢查,那么您應(yīng)該只在更改中調(diào)用此函數(shù)并將 lastSel 和 newSel 作為參數(shù)傳遞,如下所示:
$("#buildingSelect").on("change", function(){
checkDirtyStatus(lastSel, $(this).val());
});
然后,您可以將更改函數(shù)中的邏輯轉(zhuǎn)移到 checkDirtyStatus 函數(shù)中,并在那里進(jìn)行檢查。在這種情況下,如果您希望恢復(fù)選擇值而不是$(this).val(lastSel)您將執(zhí)行$("#buildingSelect").val(lastSel).
我希望這有幫助。
添加回答
舉報(bào)