HTML:無效的:需要CSS僞類不使用jQuery遍歷方法時,選擇多個表單元素相匹配的工作
<input required>
<input required>
<input required>
的JavaScript
/*
// Add script for noted :invalid check to work
// :required can also be made to work by modifying script, i.e. changing "invalid" to "required" where noted
// Source: http://stackoverflow.com/a/15821264/2171842
jQuery.extend(jQuery.expr[':'], {
invalid : function(elem, index, match){ // modify pseudo-class here
var invalids = document.querySelectorAll(':invalid'), // modify pseudo-class here
result = false,
len = invalids.length;
if (len) {
for (var i=0; i<len; i++) {
if (elem === invalids[i]) {
result = true;
break;
}
}
}
return result;
}
});
*/
$(document).ready(function(){
// works
console.log("number of invalid elements: "+$(":invalid").length); // selector matches multiple elements
console.log("is first element invalid? "+$("input:first").is(":invalid")); // selector matches one element
console.log("is at least one element enabled? "+$("input").is(":enabled")); // selector matches multiple elements
// fails without additional script, :required also fails
console.log("is at least one element invalid? "+$("input").is(":invalid")) // selector matches multiple elements
console.log("number of invalid elements: "+$("input:first").siblings(":invalid").andSelf(":invalid").length) // selector (siblings(":invalid")) matches multiple elements
});
控制檯錯誤:Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: invalid
。按照代碼中的註釋來導航問題。這是一個錯誤或只是在jQuery中不支持的功能?
小提琴
https://jsfiddle.net/cbqdp43s/
見':invalid'和':required'是CSS3選擇器,使他們無需加入jQuery的擴展選擇 –
@JairoContreras什麼是預期的結果做? – guest271314
另外,無效選擇器會根據元素的設置選擇一個值不能驗證的表單元素。這包括輸入以外的元素,例如select和textarea。資料來源:http://www.w3schools.com/cssref/sel_invalid.asp。 –