Dynamically appending id's to dynamic div'

2019-07-10 10:27发布

问题:

I'm trying to dynamically append id's to the dynamically generated div's . Initially I have the first div with class "check" & then after a "show more" button is clicked , we another div with same class gets rendered. There's an ajax call here. Here's the structure:

<div class= "check">

</div>

Show more clicked: AJAX Call

<div class= "check">

</div>

Show more clicked: AJAX Call

<div class= "check">

</div>

I want to dynamically append id's to the main & nested div. So I want the following result:

<div class= "check" id = "check_0" >
    <div id = "test0">
  <script type = 'text/javascript'>
        thirdpartyfunction(function(){});
  </script>
  </div>
</div>


<div class= "check" id = "check_1" >
    <div id = "test1">
  <script type = 'text/javascript'>
        thirdpartyfunction(function(){});
  </script>
  </div>
</div>

<div class= "check" id = "check_2" >
    <div id = "test2">
  <script type = 'text/javascript'>
        thirdpartyfunction(function(){});
  </script>
  </div>
</div>

What I tried changes id of the first div always. What the best way to go about this problem?

I tried something like this:(Pseudocode)

var count = 0; 
if(div with count id=0 does not exist then .. )
{
$(".check").attr("id","check_"+count);
count++;
}

Third party function thirdpartfunction.track(function() { test("test");})

回答1:

Use .each() of JQuery

$( ".check" ).each(function( i ) {
$(this).attr('id', 'check' + i);
$(this).append('<div id=\"test' +i+'\"></div>');
var script=document.createElement('script');
script.type='text/javascript';
script.innerHTML=" alert('"+i+"');";
$(this).find('div').append(script);
});

Here's a working jsfiddle http://jsfiddle.net/puo906vn/4/



回答2:

Use:

var count = 0; 
if($('.check').attr('id') != 'check_'+0)
{
$(".check").attr("id","check_"+count);
count++;
}


回答3:

try with this shorter way:

$(".check").each(function(key,elem){
    $(elem).attr('id', 'check_' + key)
})