我试图遍历一个表,并使用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。
如果我有大量的代码要生成呢?处理这件事最好的方法是什么?
发布于 2018-02-06 15:28:33
您面临的问题是在循环中使用公共类名,因此影响到所有元素,而不是当前迭代中的元素。
要解决这个问题,可以使用this关键字来引用.code容器中的当前a,然后需要找到svg.barcodes元素,以便在其上实例化.JsBarcode()库。试试这个:
$("#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
});
});
});<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>
https://stackoverflow.com/questions/48646379
复制相似问题