您知道如何在按钮单击时动态添加div,以及如何使用jQuery删除该div:
<input type="button" class="adddiv" value="add" />
<div class="clean">
msg
<button class="close" value="close" >
</div>
<script>
$(".adddiv").on("click",function(){
$('.clean').after('<div class="clean main1">msg<button class="close" value="close" /></div>');
});
$(document).on("click",".close",function(){
$(this).closest('div').remove();
});
</script>
但是在这里我需要限制页面中的最大干净div数为5。如果用户添加超过5个div我需要限制。
怎么做?
答案 0 :(得分:3)
我建议如下,但请注意我选择将“索引”添加到自定义data-*
属性,在本例中为data-index
,因为它避免了解析元素类的必要性 - 用于检索该索引的名称;可以使用纯JavaScript检索data-index
值:
var index = HTMLElement.dataset.index;
或者通过jQuery:
var index = $(element).data('index');
那就是我提出的解决方案:
// using the on() method to bind the anonymous function
// of that method as the event-handler for the 'click'
// event fired on the '.adddiv' element:
$('.adddiv').on('click', function() {
// caching the current '.clean' elements present on
// the page:
var cleans = $('.clean'),
// cloning the first of those elements, including
// descendants, data and event-handlers, using
// clone(true, true):
newClean = $('.clean').eq(0).clone(true, true),
// retrieving the number of '.clean' elements
// currently in the document:
num = cleans.length;
// setting the 'adddiv' <input> element to be
// disabled if after the next addition (which
// is completed within this function) there
// will be more than 6 '.clean' elements in
// the document:
this.disabled = num + 1 >= 6;
// if the current number of '.clean' elements
// is less than 6:
if (num < 6) {
newClean
// adding the value of the 'data-index' attribute,
// JavaScript is zero-indexed so the new index is
// equal to the current number of 'clean' elements:
.attr('data-index', num)
// and then we insert the cloned element after the
// last of the current '.clean' elements present
// in the document:
.insertAfter(cleans.eq(num - 1));
}
});
// using on() again to bind clicks on the elements
// matched by the supplied selector, delegating the
// event-listening to the document (although the
// closest ancestor element present in the page
// would be a better choice):
$(document).on('click', '.clean > .close', function() {
// removing the closest ancestor <div> element of
// the clicked button:
$(this).closest('div').remove();
// caching the '.clean' elements in the document
// after removing the unwanted element:
var clean = $('.clean');
// iterating over each of the (remaining) '.clean'
// elements and updating the 'data-index' property
// to be equal to the index of insertion:
clean.attr('data-index', function(i) {
// it seems likely that the first of the elements
// should have no index (from what I can see in
// the question, therefore if i (the index of
// the current element in the collection) is equal
// to zero we return an empty string, otherwise we
// return the index:
return i === 0 ? '' : i;
});
// updating the disabled property of the '.adddiv'
// <input> element, to reenable if the current
// number of 'clean' <div> elements is less than 6
// (though because we enable an element by updating
// its disabled property it does look a little
// confusing and 'backwards' almost):
$('.adddiv').prop('disabled', $('.clean').length >= 6);
});
$('.adddiv').on('click', function() {
var cleans = $('.clean'),
newClean = $('.clean').eq(0).clone(true, true),
num = cleans.length;
this.disabled = num + 1 >= 6;
if (num < 6) {
newClean.attr('data-index', num).insertAfter(cleans.eq(num - 1));
}
});
$(document).on('click', '.clean > .close', function() {
$(this).closest('div').remove();
var clean = $('.clean');
clean.attr('data-index', function(i) {
return i === 0 ? '' : i;
});
$('.adddiv').prop('disabled', clean.length >= 6);
});
/* hiding the close button if there is
only one <div> present within the
common parent */
div:only-of-type button.close {
display: none;
}
[data-index]::after {
content: attr(data-index);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="adddiv" value="add" />
<div class="clean">
msg
<button class="close">Close</button>
</div>
参考文献:
答案 1 :(得分:0)
试试这个
<input type="button" class="adddiv" value="add" />
<div class="clean">
msg
</div>
<button class="close" value="close" > Remove </button>
$(".adddiv").on("click",function(){
if($('div.main1').length <= 5){
$('.clean').append('<div class="clean main1">msg<button class="close" value="close" /></div>');
}
else{
// do something else here
alert($('div.main1').length)
}
});
$(document).on("click",".close",function(){
$(this).closest('div').remove();
});
上查看
答案 2 :(得分:0)
在每个&#39;添加&#39;事件 - 您可以使用$ .each()循环迭代.clean div,并计算添加了多少个干净的div。然后,如果已经有5个,那么你就不再添加任何div了。检查:https://api.jquery.com/each/
示例:
var counter = 0;
$('div.main1').each( function() {
counter++;
});
if(counter >= 5) {
// do nothing
}
else {
// add next div
$('.clean').after('<div class="clean main1">msg<button class="close" value="close" /></div>');
}
答案 3 :(得分:0)
我更喜欢在dom中使用html模板而不是javascript代码中的字符串。 这就是结果。
我建议不要根据项目数量使用css className,因为可能会删除5中的数字“2”并添加一个新数字,这将获得另一个数字“5”。数字'5'将重复。
$(function() {
var $wrapper = $('#clean-wrapper'),
$addButton = $wrapper.find('.adddiv'),
$itemToClone = $wrapper.find('.itemToClone');
// Add new div.
$addButton.on('click', function() {
$itemToClone
.clone()
.appendTo($wrapper)
.show();
$wrapper.trigger('mutation');
});
// Close div.
$wrapper.on('click', '.close', function() {
var $item = $(this).parents('.clean').first();
$item.remove();
$wrapper.trigger('mutation');
});
// Toggle button.
$wrapper.on('mutation', function() {
var itemCount = $(this).find('.clean:visible').length;
$addButton.prop('disabled', itemCount >= 5);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="clean-wrapper">
<input type="button" class="adddiv" value="add" />
<div class="clean itemToClone" style="display: none;">msg <button class="close" value="close" /></div>
</div>
答案 4 :(得分:0)
尝试以下代码:
HTML代码:
<input type="button" class="adddiv" value="add" />
<br/>
<div class="clean">
msg
<br/>
<input type="button" class="close" value="close" />
</div>
JS代码:
<script>
$(".adddiv").on("click",function(){
console.log($('div.clean').length);
if($('div.clean').length <= 4){
console.log("Test");
$('div.clean').last().after('<div class="clean">msg <br/><input type="button" class="close" value="close" /></div>');
}
else{
// do something else here
}
});
$(document).on("click",".close",function(){
if($('div.clean').length>1)
$(this).closest('div').remove();
});
</script>
答案 5 :(得分:0)
请尝试以下代码。最简单的解决方案:
<div id="main_container">
<div class="clean">
Message
<button class="close">CLOSE</button>
</div>
</div>
<script>
$("#adddiv").on("click",function(){
$('#main_container').append('<div class="clean">Message<button class="close">CLOSE</button></div>');
});
$(document).on("click",".close",function(){
$(this).closest('.clean').remove();
});
</script>