jQuery.contains() 无法正常工作

jQuery.contains() does not work properly

在以下情况下我应该得到一个 "alert",但我没有得到任何 "alert"。我正在尝试 jQuery.Contains().

的简单示例
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                var alpha = $.contains('body','p') {
                    alert(alpha);
            });
        </script>
    </head>
    <body>
        <p>This is a paragraph.</p>
    </body>
</html>

jQuery.contains 只有 returns boolean 并且没有回调。 试试这个代码。

$(document).ready(function(){
    alert($.contains(document.body,$('p')[0]));
});
Use this code you have error on this line (var alpha = $.contains('body','p'){)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var alpha = $.contains('body','p');
alert(alpha);
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>

根据 jQuery documentation API 仅采用元素节点(而不是 JavaScript/jQuery objects选择器)

Check to see if a DOM element is a descendant of another DOM element.

Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

您应该将代码更改为

$(function () {
   alert($.contains(document.body, $("p")[0])) //alerts true
   alert($.contains(document.body, document.getElementsByTagName("p")[0]));    //alerts true
})

试试这个:

$(document).ready(function(){
    var alpha = $.contains(document.body,$("p")[0])
    if (alpha) {
         alert(alpha);
    }
});

DEMO

Arguments are always DOM elements, not simple text.

有关详细信息,请参阅 this.