选择HTML<输入>缺少类型属性-jQuery的元素
Select HTML <input> elements with missing type attribute - jQuery
我正在编写一个脚本,该脚本应返回所有类型设置为文本、数字,电子邮件或密码的输入元素。我还希望它返回所有具有未定义类型(缺少属性)的输入字段。
有简单快捷的方法吗?
这是我迄今为止的实现:
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
}
}
type
属性的input
元素的一种简单方法是将属性选择器[type]
与:not()
伪类组合。
在这样做的过程中,我们本质上否定了所有具有type
属性的input
元素。
$('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 />
相关文章:
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的类型错误:无法读取属性'删除'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- Alfresco JavaScript,当文件上传到网站时,设置自定义类型属性
- 有没有一种方法可以通过列类型/属性来格式化MySQL单元格数据
- 如何访问javaScript Number类型属性
- 我如何使用jQuery添加与名称值相同的输入类型属性
- 任何人都知道为什么 XHTML 中没有类型属性“text/css”的