Add a barcode mulitple times based on the class before
I have a list of numbers and I need to automatically have them each turned into a barcode. I can get the first one to change, but I cannot get the ones after to change. I have a jquery barcode generator. I am pretty new to this.开发者_运维知识库 Please help.
<table width=180 border=0 cellpadding=0 cellspacing=0>
<tr>
<td class="barcode_needed">10133</td>
</tr>
<tr>
<td class="barcode_needed">20133</td>
</tr>
<tr>
<td class="barcode_needed">30133</td>
</tr>
</table>
<link rel="stylesheet" type="text/css" href="http://barcode-coder.com/css/style.css?ft=1298939919" />
<script type="text/javascript" src="http://barcode-coder.com/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="http://barcode-coder.com/js/jquery-ui-1.7.custom.min.js"></script>
<script type="text/javascript" src="http://barcode-coder.com/js/jquery-barcode-last.min.js"></script>
<script>
$("td.barcode_needed").after("<div id='bcTarget1'>");
$("#bcTarget1").barcode(('G' + $("td.barcode_needed").html()), "code128");
</script>
Your problem is that you are creating multiple <div>
elements with the same id
attribute. When you do this:
$("#bcTarget1")
jQuery will only find the first one and so you only get one barcode. You're also mixing up your elements by inserting a <div>
as a child of a <tr>
.
First, fix your HTML structure (including the duplicate id
attributes):
$('td.barcode_needed').append('<div class="bcTarget">');
This puts your <div>
inside the <td>
(so that your element nesting is correct) and replaces the id
attribute with a class
.
Then, fix the barcodes by referencing the next structure.
$('.bcTarget').each(function() {
var $this = $(this);
$this.barcode(
'G' + $this.closest('td.barcode_needed').text(),
'code128'
);
});
The closest
call goes up the tree to find the closest ancestor that matches the selector. You can just use text
on the table cells that you find as the <div>
s you just added will still be empty when you call .text
.
Live example: http://jsfiddle.net/ambiguous/eaYTZ/
You'll probably want to play with the styling a bit of course.
精彩评论