如何设置方法,该方法只能删除元素的预定义值

How to set up method, which can delete only predefined value of elements?

本文关键字:方法 删除 元素 预定义 何设置 设置      更新时间:2023-09-26

我在Jquery中有一个list和prepend()方法,每次我点击这个时,我都可以在html代码上附加新的修饰语。 我甚至可以添加 1 000 000 倍 buit 我想有一个限制。如何设置限额?例如,用户在单击按钮时,他们应该只能附加 2 次。

.html:

<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>
<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>
</body>

和jquery:

$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").prepend("<b>Prepended text</b>. ");
    });
    $("#btn2").click(function(){
        $("ol").prepend("<li>Prepended item</li>");
    });
});

你想做这样的事情吗?

var count = 0;
var limit = 5;
$(document).ready(function() {
    $("#btn1").click(function() {
        $("p").prepend("<b>Prepended text</b>. ");
    });
    $("#btn2").click(function() {
        if (count <= limit) {
            $("ol").prepend("<li>Prepended item</li>");
            count++;
        } else {
            alert('limit reached')
        }
    });
});

给它一个数据:

<button id="btn1" data-prepended="0">Prepend text</button>

然后

$("#btn1").click(function(){
    var a = parseInt($(this).data("prepended"),10);
    if(a<2){
    a++;
    $("p").prepend("<b>Prepended text</b>. ");
    $(this).data("prepended", a);
    }
});
$(document).ready(function(){
    $("#btn1").click(function(){
        if($('p>b').length<=2){
        $("p").prepend("<b>Prepended text</b>. ");
        }
    });
    $("#btn2").click(function(){
        if($('ol > li').length<5){
        $("ol").prepend("<li>Prepended item</li>");
        }
    });
});