gpt4 book ai didi

javascript - 一个元素上的多个指令不起作用

转载 作者:行者123 更新时间:2023-12-03 11:43:45 25 4
gpt4 key购买 nike

我有一个输入元素,其中有两个指令(属性)。如果输入无效,它会添加一个 error 类。

<input required alpha type="text" name="firstName" ng-model="newUser.firstName" class="form-control" maxlength="30" placeholder="First Name" />

这些是我的指令

// SHOWS AN ERROR IF THE INPUT IS EMPTY
directives.required = function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.on('keyup', function(event) {
if(elem.val().trim() == '') {
elem.prop('title', 'This input is required!');
elem.addClass('error');
} else {
elem.prop('title', '');
elem.removeClass('error');
}
})
}
}
};

// SHOWS AN ERROR IF THE INPUT CONTAINS NON ALPHA CHARACTERS
directives.alpha = function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var regexp = /^[A-Za-z ñÑ]+$/;
var char;
elem.on('keyup', function(event) {
if(!regexp.test(elem.val())) {
elem.prop('title', 'This input can contain letters only!');
elem.addClass('error');
} else {
elem.prop('title', '');
elem.removeClass('error');
}
})
}
}
};

但它没有达到我的预期。只有一个指令有效!当我尝试删除属性 alpha 时,required 现在可以工作了!有人能告诉我为什么会这样吗?

最佳答案

它们不能一起工作,因为它们会覆盖彼此的更改。我添加了额外的条件来避免这种情况:

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<input required="" alpha="" type="text" name="firstName" ng-model="newUser.firstName" class="form-control" maxlength="30" placeholder="First Name" />
</div>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', function($scope) {

}]).directive('required', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.on('keyup', function(event) {
var title = 'This input is required!';
if(elem.val().trim() == '') {
elem.prop('title', 'This input is required!');
elem.addClass('error');
} else if (elem.prop('title') == title) {
elem.prop('title', '');
elem.removeClass('error');
}
})
}
}
}).directive('alpha', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var regexp = /^[A-Za-z]*$/;
var char;
elem.on('keyup', function(event) {
var title = 'This input can contain letters only!';
if(!regexp.test(elem.val())) {
elem.prop('title', title);
elem.addClass('error');
} else if (elem.prop('title') == title) {
elem.prop('title', '');
elem.removeClass('error');
}
})
}
}
});
</script>
</body>
</html>

关于javascript - 一个元素上的多个指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26146881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com