Javascript 使用jquery创建元素并为它们提供不同的类
克隆Javascript 使用jquery创建元素并为它们提供不同的类,javascript,jquery,Javascript,Jquery,克隆.clone具有 <section class="clone"> <div class="input-group"> <input type="text" class="form-control" placeholder="insert step 2 title*"> </div> </section> 一切都好,但我的问题是;是否可以为克隆的输入指定不同的类名。喜欢 <input type="tex
.clone
具有
<section class="clone">
<div class="input-group">
<input type="text" class="form-control" placeholder="insert step 2 title*">
</div>
</section>
一切都好,但我的问题是;是否可以为克隆的输入指定不同的类名。喜欢
<input type="text" class="form-control input2" placeholder="insert
step 2 title*">
<input type="text" class="form-control input3" placeholder="insert step 2 title*">
<input type="text" class="form-control input4" placeholder="insert step 2 title*">
有没有办法做到这一点,因为在这个标记中,
“
不会将其视为一个数字?您可以使用字符串串联来实现这类功能:
var input = $("input", {"class": "input"+i);
或模板文本:
var input = $("input", {"class": `input${i}`);
您可以了解有关模板文本的更多信息
基本上,您可以使用backquote`字符创建它们,${…}
中的所有内容都被解释为代码
您应该查看MDN页面上的浏览器兼容性部分,因为并非所有浏览器都支持模板文本。在.clone()
之后,您可以执行.each()
循环所有元素,并对其中的类进行任何更改。如果它们是嵌套元素,您还需要在它们的每个子元素上运行它。如果是这样的话,您需要将类更改函数分离,以便它可以递归运行
大概是这样的:
const changeClass = element => {
// do something here to change the class name how you want for $(element)
$(element).children().each(changeClass);
};
$('.btnAnotherStep').on('click',function(){
var copy = $('.clone>*').clone().each(changeClass);
$('.container').append(copy);
});
如何处理类名取决于您自己,但这可能是某种字符串转换。您可以循环克隆的元素,在
每个
循环中获取索引,并将该索引放在模板文本中,或者传统上通过字符串连接。无需在初始单击事件之外创建其他循环:
$(function() {
$('.btnAnotherStep').on('click',function(){
var copy = $('.clone > *').clone();
copy.each(function(index, elem) {
const $this = $(this);
if ($this.is('input')) {
$this.addClass(`input${i}`);
}
});
$('.container').append(copy);
});
});
很可能,最好提及的是,上不支持模板文本
const changeClass = element => {
// do something here to change the class name how you want for $(element)
$(element).children().each(changeClass);
};
$('.btnAnotherStep').on('click',function(){
var copy = $('.clone>*').clone().each(changeClass);
$('.container').append(copy);
});
$(function() {
$('.btnAnotherStep').on('click',function(){
var copy = $('.clone > *').clone();
copy.each(function(index, elem) {
const $this = $(this);
if ($this.is('input')) {
$this.addClass(`input${i}`);
}
});
$('.container').append(copy);
});
});