简体   繁体   English

如何获得对动态添加元素的引用?

[英]How to get reference to a dynamically added element?

The following code is intended to insert a <p> element into the DOM before an already existing <p> element and then insert a table below the newly inserted <p> element (so that the table appears between the two <p> elements): 以下代码旨在将<p>元素插入到DOM已存在的<p>元素之前,然后在新插入的<p>元素下方插入一个表(以便该表出现在两个<p>元素之间) :

$("#para1").before("<p id = 'para2'>" + printDate + "</p>");
$("#para2").after("<table id = 'table'></table>"); 

However, when I try to add a row to the newly inserted table, like so: 但是,当我尝试向新插入的表中添加一行时,如下所示:

$("#table").prepend("<tr><td>asdfasf</td></tr>");

the row always gets added to a different table (with a diffrent id) that sits before the <p> element with id para2 . 该行总是被添加到另一个表(具有不同的ID),该表位于ID为para2<p>元素para2 What could be the reason for this strange behaviour? 这种奇怪行为的原因可能是什么?

This is a snapshot of the DOM inspector. 这是DOM检查器的快照。 How can the table with id 21-09-2014 be in two different places? ID为21-09-2014的表格如何位于两个不同的位置?

在此处输入图片说明

EDIT : You were all correct. 编辑 :你们都是正确的。 I had added an empty table with the same id earlier and thought it wasn't there because I couldn't see it. 我之前添加了一个具有相同ID的空表,并认为它不存在,因为我看不到它。 That brat cost me 5 hours of billable work! 那臭小子花了我5个小时的可计费工作!

The main problem for adding the entry to a different table might be duplicate ids in your page. 将条目添加到其他表的主要问题可能是页面中的ids重复。 If here are duplicate ids, the id selector will return the first element with the id. 如果此处有重复的ID,则ID选择器将返回具有ID的第一个元素。

To get the reference to newly added element use .insertBefore() and insertAfter() instead of before() and after() respectively. 为了让参考新添加的元素使用.insertBefore()insertAfter() ,而不是之前()()后分别。

var $para = $("<p id = 'para2'>" + printDate + "</p>").insertBefore('#para1');

var $table = $("<table id = 'table'></table>").insertAfter('#para2');
$table.append("<tr><td>asdfasf</td></tr>");

You're trying to prepend to a table? 您要摆在桌子前吗? Shouldn't you use 你不应该用

$('#table tr:last').after('<tr><td>asdfasf</td></tr>');

instead? 代替?

or :first and before? 或:首先和之前?

 $("#para1").before("<p id = 'para2'>The new p element with Id='para2' </p>"); $("#para2").after("<table id = 'table'><tr><td>The second row</td></tr></table>"); $("#table").prepend("<tr><td>new row inner #table and it will be the first row</td></tr>") 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="table-with-diferent-id">table with diferent id that already exist</table> <p id="para1">para 1</p> 

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

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