如何限制创建元素的次数

时间:2018-07-24 13:49:01

标签: javascript html5 function onclick createelement

是否可以限制用户单击按钮来创建元素的次数?到目前为止,这是我设法做到的。谢谢。

JavaScript

    var ClickCount = 0;

    function countClicks() {
    var clickLimit = 8 ; //Max number of clicks
    if(ClickCount<=clickLimit) {
        populateTipItem();
    }
    else if(ClickCount > clickLimit)
    {
        return;
    }
}

// TIP LIST
function populateTipItem() {

  var x = document.createElement("INPUT");
  x.setAttribute("type", "text");
  x.setAttribute("class", "form-control mt-1 tip-item");
  x.setAttribute("placeholder", "Another Tip Item! ... 250tks");
  document.getElementById("tipList").appendChild(x);
  }

HTML

    <div id="tipList" class="form-group mt-5">
      <label for="tips">Your Tip Menu Items</label>
      <small class="form-text text-muted">Max 10 items.</small>
      <input type="text" name="tips" class="form-control mt-1 tip-item" placeholder="Tip Item! ... 10tks"/>
    </div>
    <button class="btn btn-secondary" onclick="return countClicks()">Add Tip Item</button>

2 个答案:

答案 0 :(得分:4)

您快完成了。主要更改是添加ClickCount++,这样您就知道创建了多少元素。

var ClickCount = 0;
var clickLimit = 8 ; //Max number of clicks
function countClicks() {
    if(ClickCount<=clickLimit) {
        ClickCount++;
        populateTipItem();
    }
    else if(ClickCount > clickLimit) {
        return;
    }
}

答案 1 :(得分:1)

或者,您可以计算创建的元素数:

var clickLimit = 8;
var tipList = document.getElementById('tipList');

function countClicks() {
  if (tipsList.children.length < clickLimit) {
    populateTipItem();
  }
}