我在嘗試為函式的引數賦值時遇到了這種奇怪的行為,然后在 onClick 事件和我的代碼的其他部分中重用該引數。
我有一個函式fctClearAllInputs
可以清除輸入中的值,并且必須根據呼叫它的位置顯示一個確認彈出視窗。
在onClick 事件fctClearAllInputs(true)
中呼叫時,該引數被正確評估為 true。$("#idBtnCallClearFunction")
blnClearWithoutConfirmation
然而,當在onClick 事件中fctClearAllInputs
被呼叫時,它的引數是一個物件并且沒有被正確評估(一個物件值在 JS 中是真實的:)。$(".clearAllInputs")
blnClearWithoutConfirmation
!!{} == true
blnClearWithoutConfirmation
為to設定默認值false
被忽略
如果我更改fctClearAllInputs
為fctClearAllInputs(false)
inside $(".clearAllInputs")
,則引數blnClearWithoutConfirmation
正確設定為false
,但帶有類的按鈕clearAllInputs
不再可點擊。
這是什么行為,如何將值傳遞給在 JQuery 事件中呼叫的函式的引數并在我的函式中正確評估它?
請參閱下面的代碼
$(document).ready(function() {
const fctClearAllInputs = function (blnClearWithoutConfirmation = false) {
console.log(`blnClearWithoutConfirmation: '${JSON.stringify(blnClearWithoutConfirmation)}'`);
console.log(`Convert to bool: '${!!blnClearWithoutConfirmation}'`);
//blnClearWithoutConfirmation inside 'fctClearAllInputs(false)' is true but button will not be clickable
//blnClearWithoutConfirmation inside 'fctClearAllInputs' is an object evaluated to true but button will be clickable
//...
// blnClearWithoutConfirmation==true => clear inputs without confirmation popup
if (!!blnClearWithoutConfirmation) {
// clear inputs
}
// blnClearWithoutConfirmation==false => show confirmation popup then clear if user accepts
else {
// show popup
// clear inputs
}
};
// set onclick event to all buttons with class 'clearAllInputs'
$(".clearAllInputs").on("click", fctClearAllInputs); //fctClearAllInputs(false)
// button to call clear function and also do other things
$("#idBtnCallClearFunction").on("click", function() {
// DO THINGS
fctClearAllInputs(true);
// DO OTHER THINGS
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP u1T9qYdvdihz0PPSiiqn/ /3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<button class="clearAllInputs">Clear All Inputs #1</button>
<button class="clearAllInputs">Clear All Inputs #2</button>
<br/><br/><br/><br/>
<button id="idBtnCallClearFunction">
Call Clear Function
</button>
uj5u.com熱心網友回復:
jQuery 在Event
直接呼叫函式時將物件作為引數傳遞,因此不會使用默認值。您應該像在其他處理程式中一樣使用自己的匿名函式。
// set onclick event to all buttons with class 'clearAllInputs'
$(".clearAllInputs").on("click", function() {
fctClearAllInputs.bind(this)()
}); //fctClearAllInputs(false)
// button to call clear function and also do other things
$("#idBtnCallClearFunction").on("click", function() {
// DO THINGS
fctClearAllInputs.bind(this)(true);
// DO OTHER THINGS
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508430.html
標籤:javascript html jQuery
上一篇:如何重新打開winapi視窗?