JQuery adding class to cloned element

回眸只為那壹抹淺笑 提交于 2019-12-05 23:15:19

问题


This is my script:

$('.addprop').click(function() {
        $('#clone').clone().insertAfter('.addprop');
    })

I need to add a class to the new element that is being created. Is it possible?


回答1:


Yes, it is:

$('.addprop').click(function() {
        $('#clone').clone().addClass('newClass').insertAfter('.addprop');
    })

Although you're cloning an element based on its id, $('#clone'), so note that there will be two elements sharing the same id, which makes the result invalid HTML, so I'd suggest:

$('.addprop').click(function() {
        $('#clone').clone().attr('id',id += 1).addClass('newClass').insertAfter('.addprop');
    });

This will effectively add the number 1 to the end of the end of the current id value. To make this more dynamic you'd probably need to base it on a count of the number of elements of the new class-name:

$('.addprop').click(function() {
        $('#clone').clone().attr('id',id += $('.newClass').length).addClass('newClass').insertAfter('.addprop');
    });



回答2:


Sure.

After the .clone() method the current element is the clone..

$('#clone').clone().addClass('class-name-here').insertAfter('.addprop');

Notice

you will need to change the id of the clone as it must be unique in the DOM and when you clone that element, the id is cloned as well..

So better to do something like

$('#clone').clone().attr('id','newid').addClass('class-name-here').insertAfter('.addprop');


来源:https://stackoverflow.com/questions/8720432/jquery-adding-class-to-cloned-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!