jQuery:在函数中检查`nodeType == 3`

时间:2014-10-19 23:06:59

标签: jquery

展开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;
&#13;
&#13;

2 个答案:

答案 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;
}

&#13;
&#13;
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;
&#13;
&#13;

或者,根据以下评论中提供的说明:

function hasText(element) {
  return element.contents().filter(function() {
    return this.nodeType && this.nodeType === 3 && this.nodeValue.trim().length > 0;
  }).length;
}

&#13;
&#13;
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;
&#13;
&#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>

相关问题