迭代很多td来显示条形码

时间:2018-02-06 15:23:10

标签: jquery

我正在尝试通过表格并使用jquery和jsbarcode https://github.com/lindell/JsBarcode生成条形码。

理想情况下,jquery会生成所有条形码,并且只有在用户点击[显示/隐藏条形码]按钮时才显示它们。

这是html

<table>
  <tr>
    <th>Code</th>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td class="code"><a href="">38HY7</a></td>
    <td>Product 1</td>
    <td>19.99</td>
  </tr>
  <tr>
    <td class="code"><a href="#">ABC123</a></td>
    <td>Product 2</td>
    <td>29.99</td>
  </tr>
</table>
<button id="barcodes">shwo barcodes</button>

这是我的jquery

$("#barcodes").click(function() {
  $(".code > a").each(function() {
    var thecode = $(".code a").text();
    $(this).append(
      "<div class='thebars'><br /><svg class='barcodes'></div></svg>"
    );
    $(".barcodes").JsBarcode(thecode, {
      displayValue: false,
      height: 20
    });
  });
});

目前,我的脚本将所有代码存储在var代码中,但我希望它为每个代码单独执行,并在生成条形码后重置var。

如果我要生成大量代码怎么办?处理它的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您在循环中使用了常见的类名,因此您将影响所有元素,而不是当前迭代中的元素。

要解决此问题,您可以使用this关键字引用a容器中的当前.code,然后您需要找到svg.barcodes元素才能在其上实例化.JsBarcode()库。试试这个:

&#13;
&#13;
$("#barcodes").click(function() {
  $(".code > a").each(function() {
    var thecode = $(this).text();
    var $bars = $('<div class="thebars"><br /><svg class="barcodes"></div></svg>').appendTo(this);
    $bars.find('.barcodes').JsBarcode(thecode, {
      displayValue: false,
      height: 20
    });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsbarcode/3.8.0/JsBarcode.all.min.js"></script>
<button id="barcodes">Show barcodes</button>
<table>
  <tr>
    <th>Code</th>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td class="code"><a href="">38HY7</a></td>
    <td>Product 1</td>
    <td>19.99</td>
  </tr>
  <tr>
    <td class="code"><a href="#">ABC123</a></td>
    <td>Product 2</td>
    <td>29.99</td>
  </tr>
</table>
&#13;
&#13;
&#13;

相关问题