使用jquery可以设置特定输入字段的颜色吗?
如果某些验证失败,我想将其边框设置为红色,并在通过验证后将其恢复为黑色。
有什么方法可以实现这个功能吗?
$('#afieldID').addClass("error");
$('#afieldID').removeClass("error");
.error {
border: solid 2px #FF0000;
}
最好的方法是进行验证并为未通过验证的每个元素添加一个类。这将保持表单和内容之间的清晰分离。
假设以下表单:
<form id="myAwesomeForm">
<input type="text" id="A" name="A"/>
<input type="text" id="B" name="B"/>
<input type="text" id="C" name="C"/>
</form>
isFieldValid
,该函数确定有效性):;(function ($) {
// When the document is ready...
$(document).ready(function () {
// ... put a "submit" trigger on the form that checks data.
$("#myAwesomeForm").submit(function () {
// Make a list of the input fields we care about.
var fieldList = ['A', 'B', 'C'];
var areAllFieldsValid = true;
// Loop through the inputs we care about
for(var i = 0; i < fieldList.length; i++) {
// Test for validity based on some function you defined somewhere.
if (!isFieldValid("#A")) {
// Mark this field as having invalid-data (and anything else
// you want to do here).
$("#A").addClass("invalid-data");
// Make a note that we hit a false field so we can abort the submit.
areAllFieldsValid = false;
}
}
// Return true/false depending on whether we got invalid
// data. If this is false, the submit will be aborted.
return areAllFieldsValid;
});
});
})(jQuery);
然后你只需要在你的文件中定义一个CSS类:
/* My CSS file */
.invalid-data { border: 1px solid red; }