2013-04-25 44 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); 
});*/