2016-07-22 46 views
0

我得到了2个alert();并试图使用'返回错误',并期望它会起作用。返回false在JavaScript对象中不工作

$(function() { 
    var options = ['mandatory', 'email']; 
    var validation_event = { 
    mandatory: function(that) { 
     if (!$(that).val() && $(that).data('placeholder')) { 
     alert('Please fill in ' + $(that).data('placeholder') + '.'); 
     return false; // this is not working? I want to alert only one alert 
     } 
    } 
    } 

    function init() { 
    $('input,select,textarea').each(function() { 
     var self = $(this); 

     $.each(options, function(i, val) { 
     var attr = self.attr(val); // option array 
     if (typeof attr !== typeof undefined && attr !== false) { 
      validation_event[val](self); 
     } 
     }); 
    }); 
    } 

    $('#submit').click(function(e) { 
    e.preventDefault(); 
    init(); 
    }) 

}) 

正试图编写一个验证逻辑,我可以每次重复使用。

https://jsfiddle.net/m5jsscp7/

回答

1

的问题是,即使你从验证函数返回false的每个循环将继续运行。

如果验证失败,你可以从每个处理程序返回false跳过进一步执行像

$(function() { 
 
    var options = ['mandatory', 'email']; 
 
    var validation_event = { 
 
    mandatory: function(that) { 
 
     if (!$(that).val() && $(that).data('placeholder')) { 
 
     alert('Please fill in ' + $(that).data('placeholder') + '.'); 
 
     return false; // this is not working? I want to alert only one alert 
 
     } 
 
     return true; 
 
    }, 
 
    email: function() { 
 
     return true; 
 
    } 
 
    } 
 

 
    function init() { 
 
    var valid = true; 
 
    $('input,select,textarea').each(function() { 
 
     var self = $(this); 
 

 
     $.each(options, function(i, val) { 
 
     var attr = self.attr(val); // option array 
 
     if (typeof attr !== typeof undefined && attr !== false) { 
 
      valid = validation_event[val](self) && valid; 
 
     } 
 
     return valid; 
 
     }); 
 
    return valid; 
 
    }); 
 
    return valid; 
 
    } 
 

 
    $('#submit').click(function(e) { 
 
    e.preventDefault(); 
 
    console.log(init()); 
 
    }) 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" name="fname" id="fname" mandatory data-placeholder="First Name"> 
 
<input data-placeholder="Email Address" type="text" id="email" mandatory email name="email" value=""> 
 
<button id="submit">Submit</button>

+0

可我更简单的逻辑吗?只是不写太多的回报真实;可能? –

+0

为什么这不起作用? http://pastebin.com/PiGazwCW –