【问题标题】:How to limit the amount of times an element can be created如何限制可以创建元素的次数
【发布时间】:2019-01-01 04:15:47
【问题描述】:

有没有办法限制用户点击按钮创建元素的次数?到目前为止,这是我设法完成的。谢谢你。

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>

【问题讨论】:

  • 在通过标签名限制元素方面,可以使用document.getElementsByTagName().length来判断是否需要限制创建该标签的另一个元素
  • 每次点击增加ClickCount的值(顾名思义)

标签: javascript html function onclick createelement


【解决方案1】:

你快完成了。主要变化是添加了ClickCount++,这样您就可以知道创建了多少元素。

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

【讨论】:

  • 完美!太感谢了!我的脑雾太大了,谢谢你为我清除它!
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多