[英]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.