Jquery使用特殊类搜索所有标签,如果其中一个标签具有值,则只显示一个警报
Jquery seach all tags with special class if one of them has the value show only one alert
第一次访问我的小提琴
单击submit
按钮时,如果文本input
字段未更改,则会出现alert
。并且文本input
得到红色边框。
我想要的是,有多少input
字段不变,这无关紧要,只会出现一个alert
。
这是我的Jquery方法:
$(".submit").click(function (e) {
$(".textInput").each(function () {
if ($(this).val() === "input here") {
e.preventDefault();
$(this).css({
border: "1px solid #f00",
color: "#f00"
});
alert("Please input the texts in red box");
} else {
$(this).css({
border: "1px solid #DCDCDC",
color: "#000"
});
}
});
});
我该怎么做?
感谢
您只需要在执行警报之前汇总您的答案:
$(".submit").click(function (e) {
var doAlert = false; // don't alert, unless the condition sets this to 'true'
$(".textInput").each(function () {
if ($(this).val() === "input here") {
e.preventDefault();
$(this).css({
border: "1px solid #f00",
color: "#f00"
});
// instead of performing the alert inside the "loop"
// set a flag to do it once the "loop" is complete.
doAlert = true;
} else {
$(this).css({
border: "1px solid #DCDCDC",
color: "#000"
});
}
});
if(doAlert) { // do the alert just once, if any iteration set the flag
alert("Please input the texts in red box");
}
});
这样的Sth将有助于标记变量:
$(".submit").click(function (e) {
e.preventDefault();
var error = false;
$(".textInput").each(function () {
if ($(this).val() === "input here") {
$(this).css({
border: "1px solid #f00",
color: "#f00"
});
error = true;
} else {
$(this).css({
border: "1px solid #DCDCDC",
color: "#000"
});
}
});
if(error == true) alert("Please input the texts in red box");
});
只需启动一个变量,例如Count
当您的条件($(this).val()=="input here")为真时,使其计数器为1 i-e计数+=1;
最后,如果(计数>0){alert("请在红框中输入文本");}
虽然您已经接受了答案,但我建议使用一种更简单的方法:
$(".submit").click(function (e) {
e.preventDefault();
/* 1. gets the input elements,
2. sets their border-color back to that specified,
3. filters the collection, keeping only those elements without a value,
4. sets the border-color of only those empty inputs to red,
5. assigns the length property of the collection to the variable.
*/
var empties = $('.textInput').css('border-color', '#ccc').filter(function () {
return !this.value;
}).css('border-color', 'red');
// if the length is greater than zero, triggers the (single) alert:
if (empties.length) {
alert('please fill out the red-boxes');
}
});
JS Fiddle演示。
相关文章:
- 在一个javascript文件中为整个网站创建标签
- 在Flickr API的标签参数中传递一个变量
- 如何创建一个表并在单击按钮时插入此标签和文本字段
- 如何在一个网页网站中处理基于document.write()的广告标签
- 使用几个<脚本>标签不会't工作-只调用一个脚本
- 有没有一种方法可以在所有嵌套循环之后放置一个标签,以便在一步中将它们全部打断
- react-让一个元素返回两个相邻的<tr>标签
- 我可以按特定的顺序迭代一个标签中的不同数据标签吗
- 你能从另一个页面中选择标签吗
- 如何在另一个 html 标签内选择 web 元素硒 Web 驱动程序与 html 源
- 链接问题:下一个字符包含在<a>TinyMce ui TinyMce中的标签
- 注入<脚本>标签给它一个合适的位置
- 我可以遍历一个p标签并更改为ul吗
- 如何将一个标签设置为图形的整行
- Javascript - 使用