javascript - 选择缺少 type 属性的 HTML <input> 元素 - jQuery

标签 javascript jquery html dom

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

有没有一种简单快捷的方法可以做到这一点?

这是我迄今为止的实现:

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 &lt;input&gt; 元素 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246516/

相关文章:

javascript - 单击时更新输入值

javascript - 将对象与 jQuery 中的另一个对象拉起来

javascript - 将此代码放在我的 Angular 元素中的哪里?

php - 提交按钮不会设置

javascript - 如何获取 jQuery UI 选项卡元素面板并设置其中一些的可见性?

javascript - PHP 和 AJAX 不能一起工作

javascript - Duktape中,如何将一个JS源文件内容转为字节码

javascript - 如何向在 jquery 中动态创建的元素添加操作?

php - Ajax 结果为数组和 JSON.parse 错误

php - 在 html 文件中包含 html 电子邮件