我想"复制" HTML结构,更改一个元素的类和"粘贴"它。
类首先是div-1
( HTML窗口中的第12行),它应该随着每个新附加一个数字而增加,例如div-2
,div-3
相反,每个元素都是div-1
。
不要介意删除不能正常工作。我有时间给这个小提琴一个小风格,但没有时间使基本功能工作。它不相关,无关紧要。
我使代码尽可能简单,废弃了很多代码,希望它易于阅读和理解!
答案 0 :(得分:1)
我已经解决了您的问题,请尝试按照jquery代码: -
我的代码中有这些代码: -
jQuery(function($) {
var prevCount = 0;
var newCount = 2;
var newClass = 'div-' + newCount;
var prevClass = 'div-' + prevCount;
//This should toggle red sqare color but it doesn't!
$(document).on('click',' .random-div', function (event) {
event.preventDefault();
$('.random-div').toggleClass('green');
});
//New cat click
$('.new-cat').click(function (event) {
event.preventDefault();
//"Copy" form
divGroup = $('.divs').html();
//"Paste" it below old one
$('#all').append('<div class="div-wrap">' + divGroup + '</div>');
NewClass = 'div-' + newCount;
prevClass = 'div-' + prevCount;
$("#all .div-wrap:last-child .div-1").addClass(NewClass).removeClass("div-1");
//Testing
console.log('newClass: ' + NewClass);
console.log('prevClass: ' + prevClass);
console.log('------------');
console.log('newCount: ' + newCount);
console.log('prevCount: ' + prevCount);
//Change class in order to instansiate Dropzone
//$(this).closest(prevClass).attr('class', NewClass);
//Instanciate Dropzone.
/*
$('.' + newClass).dropzone() {
//Not the point of this problem but it works for only 1st appended element because other elements are
also named "div-1" <- it should increase with every "get a new one" click "div-2", "div-3" etc.
};
*/
//Increase counters by 1 in order to give next target 1 number bigger class
newCount++;
prevCount++;
});
//Not related stuff, just for functionality but still: take a peek just in case!
//Delete cat
$('.delete-cat').on('click', function(event) {
event.preventDefault();
var countCats = $('.maiden-form').length;
if ( countCats > 1 ) {
$(this).closest('.divs').remove();
}
else {
alert('Cmon! Its your last form - dont delete it! And yes, I know how to use upper comma in code, Im just tired after about 5 hours of trying to solve this problem. I hope you can help me! :)');
}
});
});
您修改过的jQuery代码: -
{{1}}
它可能对你有帮助。
答案 1 :(得分:1)
您的问题归结为您使用$(this).closest(prevClass).attr('class', NewClass)
并且存在3个问题:
$(prevClass)
永远不会有效,因为它需要$('.' + prevClass)
。
每次点击按钮时,您都会添加新的div-1
,但$(prevClass)
找不到div-1
,而是{&#39}}正在寻找div-2
,div-3
等。$(prevClass)
应为$('.div-1')
。
(可选),使用jQuery的.addClass
和.removeClass
而不是attr
属性,因为前者会保留您已添加的其他类到元素。
这是一个功能正常的jsfiddle for you
作为未来的建议,我建议您查看像angular这样的js框架,这样您就不会做很多困难的低级DOM操作,比如添加/删除/克隆元素。它变得毛茸茸!