我在 Jquery 中有一个列表和 prepend() 方法,每次单击此方法时,我都可以在 html 代码上附加新元素。我什至可以添加 1 000 000 次,但我想有一个限制。我如何设置限制?例如,用户单击按钮时,应该只能追加 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')
}
});
});
关于javascript - 如何设置方法,只能删除元素的预定义值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36127789/