1

我正在尝试查找所有输入元素,并根据我想要搜索 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);
4

3 回答 3

2

将节点推入数组而不是indexOf调用的结果:

for (count = 0; count < nodes.length; count++) {
  var node = nodes[count].id.indexOf("survey-answer");
  if (node != -1) {
    targetNodes.push(nodes[count]);
  }
}
于 2013-01-06T13:53:16.663 回答
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

于 2013-01-06T13:55:30.110 回答
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/

于 2013-01-06T13:57:15.167 回答