<p id='1'></p>
<p id='1a'><br /></p>
<p id='3success'><b>Match this</b></p>
<p id='3fail'><b>Match this</b> but not now because of this test</p>
我有一些逻辑需要跳过满足以下条件的元素
- 没有 html
- 只有 br 或 nbsp
- 只有特定类型的子元素 (b,i,img)
我可以轻松处理 1/2,但第三个我遇到了麻烦。我知道如何断言子部分,$('#3fail').children().length
但我不知道如何确定是否有附加文本。
关于如何验证 3 的任何建议?我正在一个简单的.each
函数中处理元素
$('p').each(function(){
var element = $(this)
if(matchesCondition(element)){
doLogic(element)
}
});
笔记
有人发布了答案并获得了很多赞成票,但它不起作用。这是一个测试答案的小提琴。
http://jsfiddle.net/ncapito/k87rc/
我能够修复@Kolink 的答案
http://jsfiddle.net/ncapito/9D3tg/
var getNontextNodes;
//coffeescript generated
getNontextNodes = function (nodes) {
var cnt, n, _i, _len;
cnt = 0;
for (_i = 0, _len = nodes.length; _i < _len; _i++) {
n = nodes[_i];
if (n.textContent.trim()) {
cnt++;
}
}
return cnt;
};
$("p").each(function () {
if (
(this.children.length === this.childNodes.length)
||
(getNontextNodes(this.childNodes) === this.children.length))
$(this).append("<b style='color:green'>Success</b>");
else
$(this).append("<b style='color:red'>Failed</b>");
});