Jquery条件选择器
我有条件选择器的问题。 我有一些输入字段。 我想要更改具有必需属性的空字段的边框颜色。
我尝试了什么:
$("[required='required']").css({ "border": "1px solid #FF0000", "background": "#FFEFFF" }); $("[required='required']").blur(function () { comp(this); }); $("[required='required']").keyup(function () { comp(this); }); $("[required='required']").click(function () { comp(this); }); function comp(a) { if ($(a).val() !== "") $(a).css({ "border": "1px solid #ccc", "background": "" }); else $(a).css({ "border": "1px solid #FF0000", "background": "#FFEFFF" }); }
这是一个链接: http : //jsfiddle.net/guwanchat/HjzVu/14/
我认为你的问题是你没有根据comp
函数初始化你的元素。
我修改了你的起始代码:
$("[required='required']").css({ "border": "1px solid #FF0000", "background": "#FFEFFF" });
对此:
$("[required='required']").each(function () { comp(this); });
我使用jQuery的each
函数来迭代与选择器匹配的对象,并调用comp函数来初始化它们。
jQuery.each()
描述:通用迭代器函数,可用于无缝迭代对象和数组。 具有length属性的数组和类数组对象(例如函数的参数对象)由数字索引迭代,从0到length-1。 其他对象通过其命名属性进行迭代。
这是一个小提琴: http : //jsfiddle.net/HjzVu/19/