jQuery将类添加到克隆元素 [英] JQuery adding class to cloned element

查看:57
本文介绍了jQuery将类添加到克隆元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的脚本:

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

我需要向正在创建的新元素中添加一个类.有可能吗?

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

推荐答案

是的,是:

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

尽管您要基于id$('#clone')克隆元素,但是请注意,会有两个元素共享 相同id ,这会导致结果无效的HTML,所以我建议:

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

这将有效地将数字1添加到当前id值的末尾.为了使它更具动态性,您可能需要根据新类名的元素数量进行计数:

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

这篇关于jQuery将类添加到克隆元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆