简体   繁体   English

jQuery:如何向动态添加的元素添加ID?

[英]JQuery: How to add an id to a dynamically added element?

I have a javascript which appends an element (a div) to my HTML page after the page is loaded. 我有一个JavaScript,可在页面加载后将元素(div)附加到HTML页面。 I would like to add an id to this dynamically div. 我想为这个动态div添加一个id。 How can i do that? 我怎样才能做到这一点?

Here is more information : The first js is myscript1.js and is loaded at the bottom of the HTML page. 这里是更多信息:第一个js是myscript1.js ,它被加载到HTML页面的底部。 In this script I have the following code : 在此脚本中,我具有以下代码:

$('div#existingDiv').append('<div class="newDiv">Content</div>');

The second js is myscript2.js and is loaded just after myscript1.js . 第二个js是myscript2.js,并在myscript1.js之后加载。 I would like to add an Id. 我想添加一个ID。

$('div.newDiv').attr('id','div-1234');

But it seems that div.newDiv does not exist. 但是似乎div.newDiv不存在。 I tried to get the children of div#existingDiv (with $('div#existingDiv').children() ) but it returns an empty result. 我试图获取div#existingDiv (带有$('div#existingDiv').children() ),但返回空结果。

Could someone help me? 有人可以帮我吗?

PS : I can't modify the myscript1.js so please don't suggest me to do what I want to do in the myscript1.js file. PS:我无法修改myscript1.js,所以请不要建议我做myscript1.js文件中想要做的事情。

your code seems to work. 您的代码似乎可以正常工作。 check it here: http://jsfiddle.net/2sL5T/ probably you problem is that 在这里检查: http : //jsfiddle.net/2sL5T/可能您的问题是

$('div.newDiv').attr('id','div-1234');

is executed before 在执行之前

$('div#existingDiv').append('<div class="newDiv">Content</div>');

first you need to find on what event your new html is inserted. 首先,您需要查找插入新HTML的事件。 is it happening on page load? 页面加载时会发生这种情况吗? then maybe you forgot to put your code in onload function? 那么也许您忘记了将代码放入onload函数中? http://learn.jquery.com/using-jquery-core/document-ready/ http://learn.jquery.com/using-jquery-core/document-ready/

You can do this: 你可以这样做:

$('#existingDiv div.newDiv:last').attr('id','div-1234');

This uses the fact that when you append something, it adds at the last. 这利用了以下事实:当您添加某些内容时,它会最后添加。

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

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