我正在尝试编写一个jQuery函数来搜索当前页面上所有具有“圆角”类的div,然后用一个包含一些换行符的换行表替换这些div漂亮的背景图像。见下文......jQuery:替换DOM中的嵌套元素
$(document).ready(function()
{
// For all "rounded-corners" div's on the page...
$("DIV.rounded-corners").each(function()
{
// Copy the contents of the div into a wrapping table.
var $roundedCornersContainer = $('<table cellpadding="0" cellspacing="0" class="rounded-corners-container"> \
<tr> \
<td class="corner-topleft"></td> \
<td class="corner-topright"></td> \
</tr> \
<tr> \
<td class="original-content" colspan="2">THIS IS WHERE THE CONTENT IS INSERTED</td> \
</tr> \
<tr> \
<td class="corner-bottomleft"></td> \
<td class="corner-bottomright"></td> \
</tr> \
</table>');
$roundedCornersContainer.find("TD.original-content").append($(this).html());
// Replace the original "rounded-corners" div with the populated wrapping table.
$(this).replaceWith($roundedCornersContainer);
});
});
这个伟大的工程,只要不存在任何嵌套的“四舍五入的角落”的div。如果有,那么只有最外层的div被我的包裹表取代。有趣的是,当我用degugger遍历这段代码时,所有嵌套的div实际上被检索和处理 - 它们simpy不会在屏幕上更新。 (注意:首先处理最外面的div,然后再处理每个嵌套的子项)。
- 难道是each()函数中的DOM元素变得陈旧吗?
- 我是否需要在每次迭代结束时以某种方式显式更新DOM?
- 或者有什么办法可以一次处理所有div(即不使用each()函数)?
你能不能另一个类添加到外层div,然后用它来找到你的div?如果你做了一个'$(“div.rounded-corners”),那么当然它会返回所有的div.rounded角落,即使它们嵌套在其他div.rounded角落。 – Jeemusu 2012-07-11 04:22:12
当您使用replaceWith时,应该已经删除原始的内部分隔角落。 – Willy 2012-07-11 04:32:06