我正在编写一个脚本,该脚本应返回类型设置为文本、数字、电子邮件或的所有输入元素密码。我还希望它返回所有未定义类型(缺少属性)的输入字段。
有没有一种简单快捷的方法可以做到这一点?
这是我迄今为止的实现:
inputFields = parentElem.find('input[type="text"], input[type="number"], input[type="email"], input[type="password"]');
//fields with missing type attr aren't selected
inputFieldsWithoutType = parentElem.find('input');
for (var j = 0; j < inputFieldsWithoutType.length; j++) {
if (inputFieldsWithoutType.eq(j).attr("type") === undefined || inputFieldsWithoutType.eq(j).attr("type") === null) {
inputFields = inputFields.add(inputFieldsWithoutType.eq(j)); //add to other inputFields
}
}
最佳答案
选择 input
的简单方法没有 type
的元素attribute就是结合属性选择器[type]
与 :not()
伪类。
这样做,我们基本上否定了所有 input
具有 type
的元素属性。
$('input:not([type])');
上面的选择器将选择所有没有 type
的元素属性,但如果您想选择没有 type
的元素属性和具有空/未定义type
属性(例如 <input type="" />
),那么您可以使用 .filter()
方法:
$inputFieldsWithoutType = $('input').filter(function () {
return !this.getAttribute('type');
});
示例:
$inputFieldsWithoutType = $('input:not([type])');
$inputFieldsWithoutTypeOrEmptyType = $('input').filter(function () {
return !this.getAttribute('type');
});
snippet.log('Input elements without a type attribute: ' + $inputFieldsWithoutType.length);
snippet.log('Input elements without a type attribute or an empty type: ' + $inputFieldsWithoutTypeOrEmptyType.length);
input{display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<input type="number" />
<input type="text" />
<input type="button" />
<input type=""/>
<input />
关于javascript - 选择缺少 type 属性的 HTML <input> 元素 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246516/