[英]How to add element with jquery append and set text value increase
這是我的代碼:
$("#btn").click(function() {
var total = 1;
if (total<10) {
total = total + 1;
text = '<p>text '+ total +'</p>';
$("#box").append(text);
}
});
視圖:
<button id="btn">button</button>
<div id="box"></div>
結果:
<p>text 2</p>
<p>text 2</p>
如何使每個點擊按鈕增值?
像這樣:
<p>text 1</p>
<p>text 2</p>
<p>text 3</p>
如果您在click scope
定義了total
(作為global
),那么您所嘗試的將會成功。
var total = 1;
$("#btn").click(function() {
if (total<10) {
total = total + 1;
text = '<p>text '+ total +'</p>';
$("#box").append(text);
}
});
優化代碼:
var total = 0;
$("#btn").click(function() {
if (total<10) {
$("#box").append('<p>text '+ total++ +'</p>');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.