簡體   English   中英

在JS中正確使用長度

[英]proper use of length in JS

我正在嘗試使用JS(表使用JQ Tablesorter)和條形碼jquery從表中打印標簽(條形碼)。 我的問題是我需要遍歷所有的isbn,並且每行顯示一個數字。 這是我的代碼:

    $("#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?

不,那兩條線很好。 但是另一方面,這兩個...

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM