Javascript DOM:按类型精确定位“输入”元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5924908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript DOM: Pinpointing "input" elements by their type?
提问by Danedo
I have a need to find and manipulate <input type="checkbox">
from a table. At the moment I have a very spartan function:
我需要<input type="checkbox">
从表中查找和操作。目前我有一个非常简单的功能:
function testAjaxCheckBoxes() {
var table = document.getElementById("ajax_output");
var nodeList = table.getElementsByTagName("input");
}
That is all I know how to do at the moment. I have a nodeList
object of all tags of <input>
, but I don't know how to check each one's type or attributes.
这就是我目前知道该怎么做的全部内容。我有一个nodeList
包含 的所有标签的对象<input>
,但我不知道如何检查每个标签的类型或属性。
I suppose the more general question is how do you view and manipulate attributes of any kind through DOM?
我想更普遍的问题是如何通过 DOM 查看和操作任何类型的属性?
回答by icktoofay
Once you have an element, you can use the getAttribute
, setAttribute
, and removeAttribute
methods to read, write, and remove attributes.
一旦你有一个元素,你可以使用getAttribute
,setAttribute
和removeAttribute
方法来读取,写入和删除属性。
回答by Domenic
If you have the luxury of targeting Firefox >=3.5 and IE >=8, you can use
如果你有足够的定位 Firefox >=3.5 和 IE >=8,你可以使用
document.querySelectorAll("input[type=file]")
to get an array of DOM elements as desired. See more at the MDC documentation.
根据需要获取 DOM 元素数组。在 MDC 文档中查看更多信息。
回答by Thomas Shields
.getAttribute(attr);
.getAttribute(attr);
so, if you want to check each item in the nodeList to see if it's a fileupload...
因此,如果您想检查 nodeList 中的每个项目以查看它是否是文件上传...
var nodeList = document.getElementsByTagName("input");
for(item in nodeList) {
if(nodeList[item].getAttribute("type") == "file") {
alert("i'm a file");
}
else {
alert(nodeList[item].getAttribute("type"));
}
};
回答by Itay Moav -Malimovka
If you where to use a library (you should) like JQuery/Mootools etc
It would look like that
如果你在哪里使用库(你应该)像 JQuery/Mootools 等
它看起来像那样
var inputs=$('#ajax_output input[type=checkbox]');
var inputs=$('#ajax_output input[type=checkbox]');
OR
或者
var inputs=$('ajax_output').getElements('input[type=checkbox]');`