JQuery adding class to cloned element

后端 未结 2 1116
攒了一身酷
攒了一身酷 2021-02-20 04:11

This is my script:

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

I need to add a class to

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-20 04:28

    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');
        });
    

提交回复
热议问题