我正在尝试编写一个jQuery函数,它搜索当前页面上具有“圆角”类的所有div,然后用包含一些漂亮背景图像的包装表替换这些div。见下文......
$(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 - 它们在屏幕上不会更新。 (注意:首先处理最外层的div,然后处理每个嵌套的子节点。)
答案 0 :(得分:2)
试试这个或在jsfiddle
中查看$(document).ready(function ()
{
// For all "rounded-corners" div's on the page...
var str = '<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>';
$("DIV.rounded-corners").each(function ()
{
var tmp = $(this);
var $roundedCornersContainer = $(str);
$roundedCornersContainer.insertAfter(tmp).find("TD.original-content").append(tmp);
});
});
答案 1 :(得分:1)
实现这一目标的一种方法是使用递归函数 - 将它传递给(圆角)DIV对象,首先它在替换自身之前在任何嵌套的圆角DIV上调用自身。
这是一个演示: http://jsfiddle.net/emtSS/3/
并且上面的函数递归看起来像:
function replaceDiv(div) {
// For all nested "rounded-corners" div's, recursively call this function to replace them first
div.find("DIV.rounded-corners").each(function() {
replaceDiv($(this));
});
// 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(div.html());
// Replace the original "rounded-corners" div with the populated wrapping table.
div.replaceWith($roundedCornersContainer);
};