选择HTML<输入>缺少类型属性-jQuery的元素

Select HTML <input> elements with missing type attribute - jQuery

本文关键字:类型 属性 -jQuery 元素 gt HTML lt 输入 选择      更新时间:2023-09-26

我正在编写一个脚本,该脚本应返回所有类型设置为文本数字电子邮件密码的输入元素。我还希望它返回所有具有未定义类型(缺少属性)的输入字段。

有简单快捷的方法吗?

这是我迄今为止的实现:

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 />

相关文章: