我正在尝试查找所有输入元素,并根据我想要搜索id以匹配特定关键字的元素的id。如果找到匹配项,我想将元素放在数组targetNodse
中。变量nodes
包含所有输入,当我记录数组时,我得到[-1, -1, 0, 0]
,它告诉我它找到了具有关键字survey-answer
的特定输入元素。但是我如何访问元素属性而不仅仅是告诉我它找到了它?
HTML
<input type="radio" id="poll-answer-8234" name="poll_430" value="8234">
<input type="radio" id="poll-answer-9234" name="poll_430" value="9234">
<input type="radio" id="survey-answer-7866" name="poll_430" value="7866">
<input type="radio" id="survey-answer-8998" name="poll_430" value="8998">
JS
var targetNodes, nodes, count;
targetNodes = [];
nodes = document.getElementsByTagName("input");
for (count = 0; count < nodes.length; count++) {
node = nodes[count].id.indexOf("survey-answer");
targetNodes.push(node);
}
console.log(targetNodes);
答案 0 :(得分:2)
将节点推入数组而不是indexOf
调用的结果:
for (count = 0; count < nodes.length; count++) {
var node = nodes[count].id.indexOf("survey-answer");
if (node != -1) {
targetNodes.push(nodes[count]);
}
}
答案 1 :(得分:0)
这样做: -
var targetNodes, nodes, count;
targetNodes = [];
nodes = document.getElementsByTagName("input");
for (count = 0; count < nodes.length; count++) {
node = nodes[count].id.indexOf("survey-answer");
if (node == 0)
targetNodes.push(nodes[count]);
}
alert(targetNodes);
这里targetNodes数组包含输入对象。
如果要访问输入标签的值,请在IF
条件下设置如下
if (node == 0)
targetNodes.push(nodes[count].value);
参考 LIVE DEMO 1 和其他 LIVE DEMO 2
答案 2 :(得分:0)
var targetNodes, nodes, count;
targetNodes = [];
nodes = document.getElementsByTagName("input");
for (count = 0; count < nodes.length; count++)
{
node = nodes[count].id.indexOf("survey-answer");
if (node != -1)
{
targetNodes.push(nodes[count]);
}
}
for (count = 0; count < targetNodes.length; count++)
{
alert("id: " + targetNodes[count].id +
", name: " + targetNodes[count].name +
", value: " + targetNodes[count].value);
}
这是一个用来测试它的JSFiddle:http://jsfiddle.net/leniel/YwLEu/1/