1

我試圖從表中使用JS(表使用JQ Tablesorter)和條形碼jquery打印出標籤(條形碼)。我的問題是我需要遍歷所有的isbn,它每行顯示一個數字。下面是我的代碼有:在JS中正確使用長度

$("#barcode").live('click', function(){ 
var title=""; 
var isbn=""; 
var first = ""; 
var second = ""; 
var indexGlobal = 0; 

$('#acctRecords tbody tr').each(function() 
{ 
    isbn += $(this).find('#tableISBN').html(); 
    title += $(this).find('#tableTitle').html(); 

    }); //end of acctRecords tbody function 

//Print the bar codes 

    var x=0; 
    for (x=0;x<isbn.length;x++) 
     { 


     first += '$("#'+indexGlobal+'").barcode("'+isbn[x]+'", "codabar",{barHeight:40, fontSize:30, output:"bmp"});'; 
     second += '<div class="wrapper"><div id="'+indexGlobal+'"></div><div class="fullSKU">&nbsp &nbsp &nbsp '+isbn[x]+ 
     '</div><br/><div class="title">'+title[x]+'</div></div><br/><br/>'; 
     indexGlobal++; 

     } 
var barcode = window.open('','BarcodeWindow','width=400'); 
     var html = '<html><head><title>Barcode</title><style type="text/css">'+ 
     '.page-break{display:block; page-break-before:always; }'+ 
     'body{width: 8.25in;-moz-column-count:2; -webkit-column-count:2;column-count:2;}'+ 
     '.wrapper{height: 2.5in;margin-left:10px;margin-top:5px;margin-right:5px;}'+ 
     '.fullSKU{float: left;}'+ 
     '.shortSKU{float: right;font-size:25px;font-weight:bold;}'+ 
     '.title{float: left;}'+ 
     '</style><script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script><script type="text/javascript" src="../barcode/jquery-barcode.js"></script><script>$(document).ready(function() {'+first+'window.print();window.close();});</script></head><body>'+second+'</body></html>'; 
     barcode.document.open(); 
     barcode.document.write(html); 
     barcode.document.close(); 

}); // end of click function 

我敢肯定,這個問題是與這些行:

var x=0; 
for (x=0;x<isbn.length;x++) 

例如,如果一個ISBN爲9780596515898,我在第一行得到9,7第二個,第三個8等。 如何獲得它在一行上打印出整個isbn?

回答

5

不,那兩條線都沒問題。但是,這2個,另一方面...

var isbn=""; 
... 
isbn += $(this).find('#tableISBN').html(); 

這使得isbn一個字符串。而且你只是在每次向它添加一個isbn時使得字符串變長。 "string".length會告訴你該字符串中的字符數,這就是爲什麼你每次迭代獲得一個字符的原因。

你想要一個數組來替代,你用[].push()方法追加項目。 [].length會告訴你該數組中的項目數量。

var isbn = []; 
... 
isbn.push($(this).find('#tableISBN').html()); 
for (var x=0; x<isbn.length; x++) { 
    isbn[x]; // one isbn 
} 
+0

還值得注意的是,那些「ID」重複搜索高度可疑。這不是無稽之談,但它確實似乎很腥。 – Pointy 2012-08-08 17:21:21

+0

是啊,一次在這裏的一個問題... – 2012-08-08 17:27:39

+0

@Pointy我總是開放的建議,讓我更好。 – Jim 2012-08-08 17:40:48