form.querySelectorAll( "input:not([type=hidden]), select, textarea, radio, checkbox" )什么意思
时间: 2024-06-06 17:06:02 浏览: 9
这段代码使用了 `querySelectorAll()` 方法来获取表单中所有可见的表单元素,包括 `<input>`、`<select>`、`<textarea>`、`<radio>` 和 `<checkbox>`,但排除了所有类型为 `hidden` 的 `<input>` 元素。它返回一个 NodeList 对象,其中包含了匹配的所有元素。
相关问题
var form = document.getElementById("productForm"); var visibleFormElements = Array.prototype.slice.call( form.querySelectorAll( "input:not([type=hidden]), select, textarea, radio, checkbox" ) ).filter(function (element) { return element.offsetParent !== null; }); var names = visibleFormElements.map(function (element) { return element.getAttribute("name"); });获取不到单选框、复选框的那么属性
单选框和复选框的值需要通过 element.checked 属性进行获取,可以将代码修改为以下形式:
```
var form = document.getElementById("productForm");
var visibleFormElements = Array.prototype.slice.call(
form.querySelectorAll(
"input:not([type=hidden]), select, textarea, radio, checkbox"
)
).filter(function (element) {
return element.offsetParent !== null;
});
var names = visibleFormElements.map(function (element) {
if (element.type === "checkbox" || element.type === "radio") {
return element.checked ? element.getAttribute("name") : null;
}
return element.getAttribute("name");
}).filter(function (name) {
return name !== null;
});
```
这样可以正确获取单选框和复选框的 name 属性。
form.querySelectorAll会取到display=none的元素吗
是的,`form.querySelectorAll`方法会取到`display:none`的元素。该方法会返回所有符合选择器的元素,无论其显示状态如何。如果您需要排除`display:none`的元素,请在选择器中添加`:not([style*="display:none"])`,以排除所有内联样式包含`display:none`的元素。例如:`form.querySelectorAll('input:not([style*="display:none"])')`。