2013-01-06 32 views
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); 

回答

2

推節點添加到陣列,而不是indexOf調用的結果:

for (count = 0; count < nodes.length; count++) { 
    var node = nodes[count].id.indexOf("survey-answer"); 
    if (node != -1) { 
    targetNodes.push(nodes[count]); 
    } 
} 
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

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/

相關問題