2012-09-15 44 views
2

我有一個變種,我想追加多次與jQuery。代碼是像這樣:追加多個變量與jquery

var number = 4;      //number of times the html must be appended 
html = $("<div>Content here</div>"); //The html I want to append 
$(document).ready(function() { 
    $("body").append(html * number); //Append the div multiple times 
}); 

我不知道我怎樣才能使HTML VAR附加在數VAR(4)中提到的次量?上面的代碼不起作用,我可以看到爲什麼。但我看不到解決這個問題的方法。有任何想法嗎? (我不是jQuery的專家!)

回答

0

,你可以做這樣的刪除$

$(document).ready(function() { 
    var number = 4; 
    html = "<div>Content here</div>"; 
    for(var i=0;i< number;i++)  
    { 
     $("body").append(html); 
    } 
    }); 

working demo

+0

非常感謝,非常完美! –

0

不能在jQuery對象(html)和數字(number)之間使用*運算符。 你將不得不使用一個循環它,像:

$(function() { 
var number = 4; 
    var i = 0; 
    var container = $("body"); 
    for (i = 0; i < number; i += 1) { 
    var html = $("<div>Content here</div>"); 
    container.append(html); 
    } 
}); 

編輯:html的循環。

+0

不得不刪除$否則它不會追加多次 – rahul

+0

謝謝,你是對的! –

0
Try this Code:- 


    $(function() {` 
     for (var i = 0; i<4; i++) { 
     $("body").append(("<div>Content here</div>")); 
     } 
    }); 
+0

它不會與$在這個$(「

Content here
」) – rahul

+0

是的,謝謝你說這個.... –

0

調用append多次緩慢,特別是在一個循環。僅從字符串編譯DOM對象一次,以便高效地使用array.join()和一個數組作爲字符串生成器。你也更喜歡使用appendTo而不是追加,因爲它更快。

例子:

var number = 4;      //number of times the html must be appended 
var content = "<div>Content here</div>";   //The html I want to append 
var stringBuilder = []; 
for (var i = 0; i < number; i++) { 
    stringBuilder.push(content); 
} 
$(document).ready(function() { 
    $(stringBuilder.join('')).appendTo($("body")); //Append the compiled string to the body 
});