js复制table最后一个tr里的值

function copy(){

    var tb = document.getElementById('table');

    var tr = document.querySelectorAll("#table tr:last-of-type td").value;

    alert(tr);

    var copyalbe = tr;

    var input = document.createElement("input");

    input.value = copyalbe;

    document.body.appendChild(input);

    input.select();

    document.execCommand("copy");

    input.style.display = "none";

    alert("复制成功");

  }

<table id="table" width="200" border="1" cellspacing="0">

    <tr id="cow1">

      <td>123</td>

      <td>111</td>

    </tr>

    <tr id="cow2">

      <td>123</td>

      <td>111</td>

    </tr>

    <tr id="cow3">

      <td class="copyalbe">123</td>

      <td class="copyalbe">111</td>

    </tr>

  </table>

  <input id="btn" type="button" value="复制" onclick="copy()">

我想要获取table中最后一个tr里的两个td的值并复制,但不知道如何获取值,有老哥们指教下吗?


繁花不似锦
浏览 863回答 1
1回答

皈依舞

你的要求是?1、获取到 table 最后两个 td 的值。2、将这两个值保存在粘贴板中,以便复制。<table border="1">&nbsp; <tr>&nbsp; &nbsp; <td>123</td>&nbsp; &nbsp; <td>111</td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td>123</td>&nbsp; &nbsp; <td>111</td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td>222</td>&nbsp; &nbsp; <td>333</td>&nbsp; </tr></table><input type="button" value="复制" onclick="copy()" /><br /><p>点击复制后在下边 textarea 中 CTRL+V 看一下</p><textarea cols="30" rows="10"></textarea><script>&nbsp; function copy() {&nbsp; &nbsp; let values = [...document.querySelectorAll('table tr:last-child td')].map(t => t.innerHTML);&nbsp; &nbsp; /* 相当这样:&nbsp; &nbsp; var values = [];&nbsp; &nbsp; var tds = document.querySelectorAll('table tr:last-child td');&nbsp; &nbsp; for (var i=0; i< tds.length; i++) {&nbsp; &nbsp; &nbsp; values.push(tds[i].value);&nbsp; &nbsp; }&nbsp; &nbsp; */&nbsp; &nbsp; let input = document.createElement('input');&nbsp; &nbsp; document.body.appendChild(input);&nbsp; &nbsp; input.value = values.join('+');&nbsp; &nbsp; input.focus();&nbsp; &nbsp; input.setSelectionRange(0, input.value.length);&nbsp; &nbsp; document.execCommand('copy', true);&nbsp; &nbsp; document.body.removeChild(input);&nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript