Javascript 选择器在按钮之后的第一个同级

Javascript selector first sibling after button

我的页面在 table 中包含 300 多个独特的条形码,类似于下面的 table。我为每个条形码提供了自己的下载按钮,但如何让按钮下载 紧随其后的第一个同级条形码?

<tr>
  <td>
    (product name)
  </td>
  <td>
    (other data)
  </td>
  <td>
    (even more data)
  </td>
  <td>
    <button type="button" class="downloadBarcode"></button> <!-- Download button -->
    <svg class="barcode" etc...></svg> <!-- SVG generated by JsBarcode -->
  </td>
</tr>
<tr>
  (another product with data and a barcode)
</tr>

这是我目前正在使用的脚本,但它显然只适用于长列表中的第一个条码元素:

  document.querySelector(".downloadBarcode").onclick = () => {
    svgToPng(document.querySelector('.barcode').outerHTML, (imgData) => {
      const download = document.createElement('a');
      download.href = imgData;
      download.download = 'barcode.png';
      download.click();
    });
  }

  const svgToPng = (svg, callback) => {
    const url = URL.createObjectURL(new Blob([svg], {
      type: 'image/svg+xml'
    }));
    svgUrlToPng(url, (imgData) => {
      callback(imgData);
      URL.revokeObjectURL(url);
    });
  }

  const svgUrlToPng = (svgUrl, callback) => {
    const svgImage = document.createElement('img');
    svgImage.style.position = 'absolute';
    svgImage.style.top = '-9999px';
    document.body.appendChild(svgImage);
    svgImage.onload = function() {
      const canvas = document.createElement('canvas');
      canvas.width = svgImage.clientWidth;
      canvas.height = svgImage.clientHeight;
      const canvasCtx = canvas.getContext('2d');
      canvasCtx.drawImage(svgImage, 0, 0);
      const imgData = canvas.toDataURL('image/png');
      callback(imgData);
      document.body.removeChild(svgImage);
    };
    svgImage.src = svgUrl;
  }

使用event.currentTarget获取被点击的元素。然后你可以使用 nextElementSibling 来获取它后面的元素。

document.querySelector(".downloadBarcode").onclick = (event) => {
  svgToPng(event.currentTarget.nextElementSibling.outerHTML, (imgData) => {
    const download = document.createElement('a');
    download.href = imgData;
    download.download = 'barcode.png';
    download.click();
  });
}