我正在尝试删除 div 中的所有空元素并找到了一个解决方案,但是它使用的是 CSS3 选择器,我很确定它不是跨浏览器。这是我在 FF 上的工作:
$("#container *:empty:not(img)").remove();
我正在尝试删除 div 中的所有空元素并找到了一个解决方案,但是它使用的是 CSS3 选择器,我很确定它不是跨浏览器。这是我在 FF 上的工作:
$("#container *:empty:not(img)").remove();
...它使用 CSS3 选择器,我很确定它不是跨浏览器。
是的,因为 jQuery 通过它的 Sizzle 选择器引擎为你处理了这些;更多。
如果你想在不使用的情况下这样做:empty
,它是一个相当直接的递归函数(不使用 jQuery,以避免在内存中创建大型数组):
function removeEmpties(node) {
var child, sibling;
for (child = node.lastChild; child; child = sibling) {
sibling = child.previousSibling;
switch (child.nodeType) {
case 1: // Element
if (child.nodeName !== "IMG") { // Assumes HTML, not XHTML
removeEmpties(child);
if (!child.firstChild) {
node.removeChild(child);
}
}
break;
case 3: // Text
if (child.nodeValue === "") {
node.removeChild(child);
}
break;
}
}
}
...或类似的规定。如果要删除仅包含空格的文本节点,请更改
if (child.nodeValue === "") {
至
if (child.nodeValue.replace(/\s/g, '') === "") {
您可以使用 jQuery 的 .text() 方法返回每个元素的文本内容并编写条件,例如if ($(this).text().length() < 1) $(this).remove()}
如果没有您的 html 示例,我无法更具体。