这是我的表单验证代码。在验证每个输入后,应显示alert("validation done")
。但是它会返回每个输入。这里是什么问题?
var app=angular.module('myApp',[])
app.controller('myController',function($scope){
$scope.clickMe = function(){
debugger
$form = $('#myForm');
$form.find('div input.required').each(function () {debugger
var $this = $(this)
if ($this.val().trim() == '') {
$(this).css('border', '1px solid red');
return false;
}
return true;
})
alert("validation done")
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<form id="myForm" >
<div>
<input type="text" class="required">
<input type="date" class="required">
<select class="required">
<option>AAA</option>
<option>BBB</option>
</select>
</div>
</form>
<button ng-click="clickMe()">submit</button>
</div>
&#13;
答案 0 :(得分:1)
此处警告(“验证完成”)应在验证后显示 每一个输入。
在那种情况下
alert
应位于each
循环$('#myFrom');
应更改为$('#myForm');
return false
if
<强>演示强>
var app = angular.module('myApp', [])
app.controller('myController', function($scope) {
$scope.clickMe = function() {
$form = $('#myForm');
var isValid = true;
$form.find('div input.required').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
$(this).css('border', '1px solid red');
isValid = false;
}
if (isValid) {
alert("validation done"); //notice the change in placement of this alert
}
return true;
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<form id="myForm">
<div>
<input type="text" class="required">
<input type="date" class="required">
<select class="required">
<option>AAA</option>
<option>BBB</option>
</select>
</div>
</form>
<button ng-click="clickMe()">submit</button>
</div>
答案 1 :(得分:1)
错误$('#myFrom')
应为$('#myForm')
。
你也可以使用内置的angular.element()函数,它可以在没有jQuery的情况下工作(虽然在更轻量级的版本中)并且对你的代码来说已经足够了。