鍍金池/ 問答/HTML/ js 循環(huán)獲取屬性的值

    js 循環(huán)獲取屬性的值

    請教各位怎么循環(huán)獲取td的屬性value的值
    clipboard.png

    回答
    編輯回答
    熊出沒

    <!DOCTYPE html>
    <html>
    <head>

    <title></title>

    </head>
    <body>

        <table>
        <tr class="price">
            <td value="1">i</td>
            <td value="2"></td>
            <td value="3"></td>
        </tr>
        <tr class="price">
            <td value="4"></td>
            <td value="5"></td>
            <td value="6"></td>
        </tr>
        </table>
    <script >
        let tds = document.querySelectorAll("td");
        tds.forEach((td)=>{    //相當于forEach(function(td){})
            console.log(td.getAttribute('value'));
        })
    </script>

    </body>
    </html>

    2017年2月20日 16:36
    編輯回答
    壞脾滊

    圖片描述

    2018年9月23日 19:28
    編輯回答
    小眼睛

    document.getElementsByClassName('price')這樣應(yīng)該會獲取到一個數(shù)組,然后去數(shù)組里找他的children,里面應(yīng)該有td,然后再去找td的value屬性。遇到這種問題,就先把dom打印出來,然后根據(jù)打印出的對象一層一層來找。

    2017年10月19日 09:07
    編輯回答
    膽怯
      var trs = document.querySelectorAll('.price');
      var arr = [];
      trs.forEach(function( tr ){
        var td = tr.querySelectorAll("td");
        arr.push({
            //常見坑  在獲取非固有屬性時應(yīng)用getAttribute()直接寫屬性名會獲取不到
          id : td[0].getAttribute("value"),
          num : td[1].getAttribute("value"),
          money : td[2].getAttribute("value")
        })
      });
      //打印結(jié)果數(shù)組中的每每項對應(yīng)一行 以對象形式保存數(shù)據(jù)
      console.log(arr);//[{id:"",money:"",num:""},{id:"",money:"",num:""}]
    2017年5月8日 16:53