说我有如下的元素序列:
<div style="margin-bottom:9px;line-height:normal;margin-top:4px"></div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">Something Here</div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">
下面有未公开的元素,我想删除它们,因为它们破坏了设计布局。那么请告诉我如何查找和删除上面未封闭和空的元素:
<div style="margin-bottom:9px;line-height:normal;margin-top:4px"></div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">
非常感谢您的帮助。
编辑建议:首先,编辑源代码实际上是不可能的。因为它们是像这样的百页,我需要一个快速的解决方案:(我没有写那些代码,但我现在必须维护,我需要临时但工作的解决方案。他们是静态的所以我不能使用服务器端此时的代码因为它们都是html文件。
编辑建议2: 结构实际上是一样的。
HTML损坏:
<div style="margin-bottom:9px;line-height:normal;margin-top:4px"></div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">Something Here</div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">
<div style="margin-bottom:9px;line-height:normal;margin-top:4px"></div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">Something Here</div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">
应该如何:
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">Something Here</div>
<div style="margin-bottom:9px;line-height:normal;margin-top:4px">Something Here</div>
没有内在的div或其他任何东西,它非常简单。
答案 0 :(得分:5)
JQuery不会操纵XML / HTML结构,只会操纵DOM和DOM的表示形式。我相信JQuery不可能做那样的事情。
最好的办法是通过W3C验证器运行您的页面。
答案 1 :(得分:4)
进行此类操作时要小心,因为可能很难确定哪个标签是未关闭的标签。
例如
<div> some text <div> more text</div>
这是未公开的div。第一个还是第二个?
答案 2 :(得分:2)
我不认为删除未关闭的元素可以用javascript完成,因为JS在浏览器构造的DOM上工作。
考虑例如:
<div id="d1">
<div id="d2">
</div>
哪个div
未公开,1或2?浏览器可能会认为第一个被关闭而第二个被关闭并相应地构建DOM,但情况并非总是如此。
要实现您的目标,您需要使用比HTML更严格的标记,例如XHTML和某种预处理器,它可以在将文档交给浏览器之前正确解析文档。
修改强>
以下是chrome如何解释此标记。请注意html文档中不存在的结束</div>
标记。
chrome dom http://img138.imageshack.us/img138/794/dom.png
这实际上给了我一个主意。如果你要在你的jquery代码可以查找的文档末尾粘贴一个元素,并且可以删除包装它的任何元素,那该怎么办?像这样:
<div id="d1">
<div id="d2">
</div>
...
<div id="myLastDiv"></div>
</body>
和JQuery:
while ($("#myLastDiv").parent()[0].tagName.toLowerCase() != "body")
{
var html = $("#myLastDiv").parent().html();
$("#myLastDiv").parent().replaceWith(html);
}
只要您的脚本块不在已损坏的元素中,这实际上在Firefox和Chrome以及IE8中都有效。
但是可以删除空元素:
$(":empty").remove();
答案 3 :(得分:1)
我认为你最好在源头修复它。这只是无论如何都无效。
答案 4 :(得分:1)
我宁愿通过Tidy解析页面,它可以解决大多数问题,并提供了几乎任何你想要的风格的选项。