2015-12-05 31 views
0

我有一个表。大多数列只包含文本,但两个包含“选择”框。的selectedIndex是不正确的

我在表中试图环和提取所选择的选项的值。

我已经能够尽可能得到尽可能试图让在我遇到了这个问题selectedIndex处的期权价值时,访问选择框,但随后。 selectedIndex始终显示为“未定义”。

继承人一些代码:

var table = document.getElementById("inTable"); 

    for (var i = 0, row; row = table.rows[i]; i++) { 
     //iterate through rows 
     //rows would be accessed using the "row" variable assigned in the for loop 
     for (var j = 0, col; col = row.cells[j]; j++) { 
     //iterate through columns 
     //columns would be accessed using the "col" variable assigned in the for loop 
     if (col.nodeName === 'TD') { 
      // select box 
      if (j === 4) { 
       var htmlString = col.innerHTML; 
       var parser = new DOMParser(); 
       var doc = parser.parseFromString(htmlString, "text/html"); 
       var e = doc.getElementById('sel'); 
       console.log(e.selectedIndex); // -> undefined 
      }     
     }    
     } 
    } 

也使用console.log(e.options[e.selectedIndex].value);

当我得到一些价值,但它们不与所选择的实际值,首先我得到0的,这实际上相当于到选择框中的第一个值,但是然后我将选择的第一个值切换到9,并且仍然得到了0的console.log(e.options[e.selectedIndex].value);

我很困惑,并且可能以错误的方式抛弃了这个!有人能让我挺直吗?

回答

0

我不明白为什么你通过你的表格的单元格循环。

如果您正在使用的ID,以确定您选择的标签,你可以简单地使用document.getElementById('your-id');

0

你不需要用就用的DOMParser查询选择的选择指标,其实你可以一类分配给您的选择,并使用document.getElementsByClassName(“yourclass”)查询它们,然后为他们每个人只读过的selectedIndex。

var selects = document.getElementByClassName('classname'); 
for(var i = 0, len = selects.length; i < len; i++){ 
    console.log(selects[i].selectedIndex); 
} 

此外,每个元素的id属性应该是唯一的,似乎所有的选择都具有相同的id“sel”。

+0

我已经决定要拍我原来的想法在脸上和尝试别的东西!不管怎么说,多谢拉。 – ThriceGood