单击使用Javascript

时间:2019-07-07 17:16:33

标签: javascript

我刚接触Javascript。我想创建以下内容:

  1. 单击表中第1列中一行的单元格。在我的示例Cell1中。
  2. Cell2和Cell3将被复制到剪贴板,但不能复制到Cell4。
  3. 它们之间将以“-”分隔

示例:

单击“ Cell1”。它将被复制到剪贴板:“ Cell2-Cell3”。

我已经尝试了几个小时,但是无法完全弄清JS。

预先感谢您的帮助。

示例表:

<html>

<body>
  <table>
    <tr>
      <th>Column1</th>
      <th>Column2</th>
      <th>Column3</th>
      <th>Column4</th>
    </tr>
    <tr>
      <td>Cell1</td>
      <td>Cell2</td>
      <td>Cell3</td>
      <td>Cell4</td>
    </tr>
  </table>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您可以尝试这样,它是一种新颖的javascript。

我使用了filterreduce数组函数

const cells = [...document.querySelectorAll('tr td')]

function getOtherCells(e) {
 const otherCells = cells.filter(cell => e.target !== cell);
 const text = otherCells.reduce((acc, cell, idx) => {
   return idx===0? `${cell.innerText}`:`${acc} - ${cell.innerText}`;
 }, "");
 console.log(text)
}

cells.forEach(cell => cell.addEventListener("click", getOtherCells))
th, td {
border: 1px solid black;
}
<html>

<body>
  <table>
    <tr>
      <th>Column1</th>
      <th>Column2</th>
      <th>Column3</th>
      <th>Column4</th>
    </tr>
    <tr>
      <td>CellOne</td>
      <td>CellTwo</td>
      <td>CellThree</td>
      <td>CellFour</td>
    </tr>
  </table>
</body>

</html>

欢迎加入,希望对您有所帮助:)