使用计数器和amp;添加Div的点击次数限制 [英] Add Div's on Click with counter & limit
问题描述
我想用下面的代码添加一些功能,只有5次才能单击添加按钮.
I would like to add some functionality with the below code that only 5 times one can click the add button.
我也想为每个复制添加一个删除按钮,因此当单击时,删除div并减少5次计数.
Also I would like to add a delete button with every replicated so when clicked, div is deleted and the counter of the 5 times is decreased.
HTML:
<button id="button" onlick="duplicate()">Add another plan</button>
<div id="duplicater">
<p>Choose Your Mobile Plan</p>
<select>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
</div>
JS:
document.getElementById('button').onclick = duplicate;
var i = 0; var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone); }
可以在此处找到JSFiddle: http://jsfiddle.net/7x4re/
A JSFiddle can be found here: http://jsfiddle.net/7x4re/
推荐答案
您可以添加一个按钮来删除元素,如下所示:
You can add a button to delete the element like this:
<button id="button">Add another plan</button>
<div id="duplicater">
<p>Choose Your Mobile Plan</p>
<select>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
<button class='removebutton'>Delete</button>
</div>
您可以启用使用jquery单击该函数的功能:
You can enable a function to fire when it's clicked using jquery:
$('body').on('click', ".removebutton", remove);
最后,删除处理程序可以删除所单击的元素:
Finally, the remove handler can remove the clicked element:
function remove() {
if (count > 1) {
if ($(this).parent().attr('id') != 'duplicater') {
$(this).parent().remove();
count--;
} else {
alert("You can't delete the first plan");
}
} else {
alert("You can't delete the first plan");
}
}
我对ReeCube使用了类似的计数器.
I've used a similar approach to the counter as used by ReeCube.
由于它使用jquery,因此您需要从本地计算机或其他位置将其包括进来.
As this uses jquery, you need to include it, either from your local machine or from somewhere else e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
所有js代码都应包装在标准的jQuery ready函数中:
All the js code should be wrapped in the standard jquery ready function:
$(function(){
// Put your js code here.
});
这篇关于使用计数器和amp;添加Div的点击次数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!