动态地将id添加到jquery中的动态div [英] Dynamically appending id's to dynamic div's in jquery

查看:68
本文介绍了动态地将id添加到jquery中的动态div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态地将id添加到动态生成的div中。最初我有第一个divclass&然后在单击显示更多按钮后,我们将呈现具有相同类的另一个div。这里有一个ajax电话。结构如下:

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>

显示更多点击:
AJAX致电

Show more clicked: AJAX Call

<div class= "check">

</div>

显示更多点击:
AJAX致电

Show more clicked: AJAX Call

<div class= "check">

</div>

我想动态地将id添加到主&嵌套的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>

我尝试改变第一个div的id总是。什么是解决这个问题的最佳方法?

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++;
}

第三方函数

thirdpartfunction.track(函数(){test(test);})

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

推荐答案

使用JQuery的.each()

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

这是一个工作的jsfiddle http://jsfiddle.net/puo906vn/4/

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

这篇关于动态地将id添加到jquery中的动态div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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