0
我有些想要做的工作,但有一個問題:它爲每個更改的輸入元素數量執行我的btnSave函數。這裏是我的代碼:刪除單擊處理程序如果表單字段爲空
$('#base-stats').on('change', 'input', function(){
$('#btn-save').bind('click', btnSave);
});
function btnSave(){
var valid = 1;
character.currentChar.charName = $('#charName').val();
character.currentChar.charLevel = $('#charLevel').val();
character.currentChar.charLife = $('#charLife').val();
character.currentChar.charES = $('#charES').val();
character.currentChar.charInt = $('#charInt').val();
character.currentChar.charStr = $('#charStr').val();
character.currentChar.charDex = $('#charDex').val();
$('#base-stats input').each(function(){
if ($(this).val().length <= 0) {
console.log('Null field found at '+$(this).attr('id'));
$('#btn-save').unbind('click', btnSave);
valid = 0;
}
});
if (valid) {
$.post('checkchar.php',
{c:character.currentChar.charName},
function(data){
if (data == 'null') {
$.post('savechar.php',
{c:character.currentChar},
function(data){
alert('Character successfully saved to the database.');
}
);
}
else {
if (confirm('Duplicate character name exists in the database! Overwrite current character?')) {
$.post('savechar.php',
{c:character.currentChar},
function(data){
alert('Character successfully updated in the database.');
}
);
}
}
}
);
}
}
因此,目前的工作,我的「保存按鈕」格開始沒有綁定任何東西的方式,那麼當一個表單輸入字段更改其綁定我btnSave處理函數div時我點擊它。爲了說明我的問題,可以說我在我的7個輸入字段中輸入了兩個值。控制檯然後登錄5個空字段過兩次,因爲兩個字段改爲:
Null field found at charLife global.js:80
Null field found at charES global.js:80
Null field found at charInt global.js:80
Null field found at charStr global.js:80
Null field found at charDex global.js:80
Null field found at charLife global.js:80
Null field found at charES global.js:80
Null field found at charInt global.js:80
Null field found at charStr global.js:80
Null field found at charDex global.js:80
我怎樣才能防止這種情況發生,仍然確保不空字段被貼到我的服務器?或者我應該使用不同的方法,例如檢查我的savechar.php
文件中的空數組值?儘管爲了節省時間,我寧願儘量減少與服務器的交互。