简体   繁体   中英

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 . I made a dummy too( fiddle ). in this fiddle every time I am putting "a" as text in div . 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. following is my code(my code is too big so I'm putting dummy form).. HTML:

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

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:

$('.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() . 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


If you wanted to return a cloned element within .html() that can be done in exactly the same way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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