2016-03-21 3 views
0

Ich habe eine Liste und prepend() -Methode in Jquery, jedes Mal, wenn ich darauf klicke, kann ich neue Elemente an HTML-Code anhängen. Ich kann sogar 1 000 000 mal hinzufügen, aber ich möchte ein Limit haben. Wie kann ich Grenzen setzen? Zum Beispiel, Benutzer, wenn sie auf die Schaltfläche klicken, sollten sie in der Lage sein, nur 2 mal anzuhängen.Wie man Methode einstellt, die nur vordefinierten Wert der Elemente löschen kann?

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> 

und jquery:

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

Antwort

1

Geben Sie sich ein Datum:

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

Und dann

$("#btn1").click(function(){ 
    var a = parseInt($(this).data("prepended"),10); 
    if(a<2){ 
    a++; 
    $("p").prepend("<b>Prepended text</b>. "); 
    $(this).data("prepended", a); 
    } 
}); 
2

Sie möchten so etwas machen?

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') 
     } 
    }); 
}); 
1
$(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>"); 
     } 
    }); 
}); 
Verwandte Themen