展开Using .text() to retrieve only text not nested in child tags - 如何将关于检查nodeType == 3
的答案转换为函数?
function hasText(element) {
element.contents().filter(function () {
if (element.contents().nodeType == 3) {
return true
}
});
}
$('p').each(function () {
if(hasText($(this))) {
$(this).css('border', '5px solid blue');
}
});

<!-- Should return true -->
<p>Hello</p>
<p>Hello <a>there</a></p>
<!-- Should return false -->
<p><a>Hello</a></p>
<p><a href="#"><img src="#"></a>
&#13;
答案 0 :(得分:1)
我建议:
function hasOnlyText(element) {
// checking if the number of contents of the element is equal to
// the number of contents that are textNodes:
return element.contents().length === element.contents().filter(function() {
return this.nodeType && this.nodeType === 3;
}).length;
}
function hasOnlyText(element) {
return element.contents().length === element.contents().filter(function() {
return this.nodeType && this.nodeType === 3;
}).length;
}
$('p').each(function() {
console.log(hasOnlyText($(this)));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Should return true -->
<p>Hello</p>
<!-- Should return false -->
<p><a>Hello</a>
</p>
&#13;
或者,根据以下评论中提供的说明:
function hasText(element) {
return element.contents().filter(function() {
return this.nodeType && this.nodeType === 3 && this.nodeValue.trim().length > 0;
}).length;
}
function hasText(element) {
return element.contents().filter(function() {
return this.nodeType && this.nodeType === 3 && this.nodeValue.trim().length > 0;
}).length > 0;
}
$('p').each(function() {
console.log(hasText($(this)));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Should return true -->
<p>Hello</p>
<!-- Should return false -->
<p><a>Hello</a>
</p>
<!-- Should also return true -->
<p>Paragraph text <a>Link text</a>
</p>
&#13;
参考文献:
答案 1 :(得分:1)
您需要返回一个值。此外,Array.prototype.every
可能比filter
更合适。
function hasText(element) {
return Array.prototype.every.call(element.contents(), function (c) {
return c.nodeType === 3;
});
}
$('p').each(function () {
if (hasText($(this))) {
$(this).css('border', '5px solid blue');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Should return true -->
<p>Hello</p>
<!-- Should return false -->
<p><a>Hello</a></p>