获取 table 行内 select 的 selected 值未按预期工作

Get selected value of select inside table row not working as expected

大家好,Whosebug 的朋友们, 我想为 javascript 中的某种 table 实现一个过滤器。我的文本搜索确实按预期工作,但我在使用 js 获取 "select" 元素时遇到一些问题...

它的一些代码:

    function doSomething(){
     var table, tr, td, i;
     
     table = document.getElementById("myTable");
     tr = table.getElementsByTagName("tr");
     for(i = 0; i < tr.length-1; i++){
      td = tr[i].getElementsByTagName("td")[2];
      
      var e = td.getElementById("ABC");
      
      if(document.getElementById("cb1").checked &&  e.options[0].value == 0){
       tr[i].style.display = "none";
       
      }else{
       tr[i].style.display = "";
      }
     }
    }
<label>click me <INPUT type="checkbox" id="cb1" onclick="doSomething();"></label>
    
    <table id="myTable">
    
    <tr><td>Something</td><td>Some other Thing</td><td><select id="ABC"  name="sel1">
    <option value=0>Default</option>
    <option value=1>Not Default</option>
    </select></td></tr>
    
    </table>

https://jsfiddle.net/tnufmuLu/3/

我已经更新了你的 fiddle 并创建了一个新的 DEMO

我已经更正了您代码中的一些错误:

for(i = 0; i < tr.length; i++){

var e = document.getElementById("ABC");

此外,我将 javascript 代码放在 <script> 标记中 HTML 代码的顶部,因为它给出了 undefined function 错误。

您可以像这样更新您的代码

function doSomething(){
    var table, tr, td, i;

    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    console.log(tr);
    for(i = 0; i < tr.length; i++){
        td = tr[i].getElementsByTagName("td")[2];
        var e = td.getElementsByTagName("select")[0];
        alert('selected value is:' + e.options[e.selectedIndex].value);
        if(document.getElementById("cb1").checked &&  e.options[0].value == 0){
            tr[i].style.display = "none";

        }else{
            tr[i].style.display = "";
        }
    }
}

此处更新demo 如果要获取下拉列表的选定值,可以使用其 selectedIndex 属性。

顺便说一下,我们不应该定义多个具有相同 ID 的 HTML 元素(请检查 here