简体   繁体   English

在克隆过程中更改div的文本

[英]change the text of a div during clone

I am appending div 's with ajax call, for this I made a dummy div , I am cloning the div and putting the data according to the data present JSON . 我用ajax调用追加了div ,为此我创建了一个虚拟divcloningdiv并根据存在的JSON数据放置了数据。 I made a dummy too( fiddle ). 我做了一个假的太( 小提琴 )。 in this fiddle every time I am putting "a" as text in div . 每次我在div中将“ a”作为文本输入时,都会出现这种情况。 I want if JSON has particular value then the text should be changed(according to fiddle if value of i is 4 then text should be 'b' instead of 'a').. so how to do it. 我想如果JSON具有特定值,则应更改文本(根据i的值为4时,则文本应为“ b”而不是“ a”)..怎么做。 following is my code(my code is too big so I'm putting dummy form).. HTML: 以下是我的代码(我的代码太大,因此我要放置虚拟表单).. HTML:

<div class="wrp"></div>
<div class="childd"></div>

CSS: CSS:

.wrp{
  background-color:#aaf;
  border:1px solid orange;
  float:left;width:100%
}
.wrp .child{
  float:left;
  height:20px;
  width:20px;
  background-color:#77c;
  border:1px solid #cdcdcd;
}
.childd{
  height:20px;
  width:20px;
  background-color:#cdcdcd;
}

JS: JS:

$('.childd').on('click',function(){
    for(i=0;i<=9;i++){
        $('.childd')
            .clone()
            .removeClass('childd')
            .addClass('child')
            .html('a')
            .appendTo('.wrp');
    }    
})

Fiddle 小提琴

If you like, you can pass a function to html() . 如果愿意,可以将函数传递给html() The return value will be what is applied, of course: 当然,返回值将是所应用的:

$('.childd').on('click',function(){
    for(i=0;i<=9;i++){
        $('.childd')
            .clone()
            .removeClass('childd')
            .addClass('child')
            .html(function(){
                return i==4 ? 'b' : 'a'   
            })
            .appendTo('.wrp');
    }    
})

JSFiddle 的jsfiddle


If you wanted to return a cloned element within .html() that can be done in exactly the same way: 如果要在.html()中返回一个克隆的元素,可以使用完全相同的方法来完成此操作:

.html(function(){
    return i==4 ? $(elem).clone() : 'a'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM