我正在尝试编写一个jQuery函数,它搜索当前页面上的所有div,这些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实际上都会被检索和处理--它们simpy不会在屏幕上更新。(注意:首先处理最外层的div,然后处理每个嵌套的子元素)。
发布于 2012-07-11 04:59:50
试试这个或在小提琴中查看
$(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);
});
});发布于 2012-07-11 05:02:15
实现这一目标的一种方法是使用递归函数--传递给它一个(圆角) 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);
};https://stackoverflow.com/questions/11425335
复制相似问题