[英]How to add element with jquery append and set text value increase
Here's my code: 这是我的代码:
$("#btn").click(function() {
var total = 1;
if (total<10) {
total = total + 1;
text = '<p>text '+ total +'</p>';
$("#box").append(text);
}
});
View: 视图:
<button id="btn">button</button>
<div id="box"></div>
Result: 结果:
<p>text 2</p>
<p>text 2</p>
How to make value increase every click button? 如何使每个点击按钮增值?
Like this: 像这样:
<p>text 1</p>
<p>text 2</p>
<p>text 3</p>
If you define total
out the of the click scope
(as global
) you will be succeed what you've tried. 如果您在
click scope
定义了total
(作为global
),那么您所尝试的将会成功。
var total = 1;
$("#btn").click(function() {
if (total<10) {
total = total + 1;
text = '<p>text '+ total +'</p>';
$("#box").append(text);
}
});
Optimized Code: 优化代码:
var total = 0;
$("#btn").click(function() {
if (total<10) {
$("#box").append('<p>text '+ total++ +'</p>');
}
});
Demo: https://jsfiddle.net/qe0h459d/ 演示: https : //jsfiddle.net/qe0h459d/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.