2013-04-25 43 views
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文件中的空數組值?儘管爲了節省時間,我寧願儘量減少與服務器的交互。

回答

1

你的btnSave()方法似乎很好。你的問題是,每次#base-stats改變時,你都會將該方法綁定到#btn-save的點擊事件。你爲什麼這樣做?所有你需要做的就是在開始時綁定一次,然後當單擊#btn-save時btnSave()會運行,並且你的驗證檢查將會啓動並執行你想要的操作。只需將腳本的頂部改爲此(我將不必要的東西放在那裏,然後將其評論出來,以便您可以看到):

$('#btn-save').click(btnSave); 
/**$('#base-stats').on('change', 'input', function(){ 
    $('#btn-save').bind('click', btnSave); 
});*/