首页 > 解决方案 > 脚本没有得到 innerHTML?

问题描述

我这里有这个 HTML

<div id="team_players">
  <h3>Players</h3>
  <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻&lt;/button>
  <table>
    <thead>
      <tr>
        <th>Name(s)</th>
        <th>Inventory</th>
        <th>Playtime</th>
        <th>Notes</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <tr data-player-ref="1">
        <td>Scriptist.<br>Scriptist.<br>HollowPresenter<br></td>
        <td><img src="img/item/item_shredder_g.png"><img src="img/item/block.png"></td>
        <td>4:13:20</td>
        <td><u style="color: #0F0">Online</u><u style="color: #0FF">Captain [1]</u><br><u style="color: #F00">Possible Alias of Snogg &lt;0&gt; [BANNED]</u></td>
        <td><br></td></tr><tr data-player-ref="13">
        <td>Snogg<br></td>
        <td></td>
        <td>9:01</td>
        <td><u style="color: #F00">Banned</u><br><u style="color: #FFF">Possible Alias of HollowPresenter &lt;0&gt;</u></td>
        <td><button class="btn-small btn-orange" onclick="teamAct('unban',13);">Un-Ban</button></td>
      </tr>
    </tbody>
  </table>
</div>

我正在尝试获取第二个<td>元素的 innerHTML。下面是我的脚本:

var Userinventory = document.querySelectorAll('tr[data-player-ref] > td:nth-of-type(2)' );

Userinventory.forEach(getinventoryitems)

function getinventoryitems(item, index) {
  var useritems = item.innerHTML[0];
  console.log(useritems);
}

为什么这不会得到innerHTML?哪个应该返回这样的东西

<td><img src="img/item/item_shredder_g.png"><img src="img/item/block.png"></td>

标签: javascriptjqueryhtml

解决方案


你有一个无关[0].innerHTML,它只得到第一个字符。

var Userinventory = document.querySelectorAll('tr[data-player-ref] > td:nth-of-type(2)'); 
Userinventory.forEach(getinventoryitems)

function getinventoryitems(item, index) {
  var useritems = item.innerHTML;
  console.log(useritems);
}
<div id="team_players">
  <h3>Players</h3>
  <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻&lt;/button>
  <table>
    <thead>
      <tr>
        <th>Name(s)</th>
        <th>Inventory</th>
        <th>Playtime</th>
        <th>Notes</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <tr data-player-ref="1">
        <td>Scriptist.<br>Scriptist.<br>HollowPresenter<br></td>
        <td><img src="img/item/item_shredder_g.png"><img src="img/item/block.png"></td>
        <td>4:13:20</td>
        <td><u style="color: #0F0">Online</u><u style="color: #0FF">Captain [1]</u><br><u style="color: #F00">Possible Alias of Snogg &lt;0&gt; [BANNED]</u></td>
        <td><br></td></tr><tr data-player-ref="13">
        <td>Snogg<br></td>
        <td></td>
        <td>9:01</td>
        <td><u style="color: #F00">Banned</u><br><u style="color: #FFF">Possible Alias of HollowPresenter &lt;0&gt;</u></td>
        <td><button class="btn-small btn-orange" onclick="teamAct('unban',13);">Un-Ban</button></td>
      </tr>
    </tbody>
  </table>
</div>


推荐阅读