问题
HTML
<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
});
Console error: Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: invalid
. Follow comments in code to navigate problem. Is this a bug or just an unsupported feature in jQuery?
Fiddle
https://jsfiddle.net/cbqdp43s/
回答1:
Is this a bug or just an unsupported feature in jQuery?
Unsupported features. :invalid
, :required
are not a jQuery extended selectors . See Category: jQuery Extensions
Though Has Attribute Selector [name] $("[required]")
should return expected results for element having required
attribute.
See also :invalid
The
:invalid
CSS pseudo-class represents any<input>
or<form>
element whose content fails to validate according to the input's type setting.
来源:https://stackoverflow.com/questions/34709088/invalid-and-required-css-pseudo-classes-dont-work-with-jquery-traversing-meth