jQuery.contains() does not work properly

爷,独闯天下 提交于 2019-12-10 16:01:19

问题


I should get an "alert" in the following case, but I am not getting any "alert". I am trying a simple example of 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>

回答1:


As per the jQuery documentation the API takes only element nodes (not JavaScript/jQuery objects or selectors)

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.

you should change the code to

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



回答2:


Try this:

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

DEMO

Arguments are always DOM elements, not simple text.

For more details, see this.




回答3:


jQuery.contains only returns boolean and doe not have a callback. Try this code.

$(document).ready(function(){
    alert($.contains(document.body,$('p')[0]));
});



回答4:


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>


来源:https://stackoverflow.com/questions/29691398/jquery-contains-does-not-work-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!