簡體   English   中英

如何使用jquery添加元素並設置文本值增加

[英]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>');
     }
});

演示: https : //jsfiddle.net/qe0h459d/

暫無
暫無

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

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