开发者

Jquery - contains method returning unexpected results

The esample is here: http://jsfiddle.net/SsPqS/

I have a div with class="record" I add a click function to every object with class"recor开发者_运维技巧d". in the click function I have this:(simplified)

$(".record").click(function(e) {
                if (!$(e.target).is(':button')) {
                    if ($.contains($(this).parents(".parentDiv"), $("#UserInformation"))) {
                        alert("true");
                    } else {
                        alert("false");
                    }
                }
            });

I keep getting the true alert, but i'm not sure why becaue #UserInformation is certinly not in the div with class "parrentDiv"

Am i using the contains function wrong?

Thanks!


$.contains() is intended to take DOM elements, like this:

if ($.contains($(this).closest(".parentDiv")[0], $("#UserInformation")[0])) {

You can test the updated demo here.


I think you should use the has() method

$(".record").click(function(e) { 
    if (!$(e.target).is(':button')) { 
        if ($(this).closest(".parentDiv").has("#UserInformation").length) {             
            alert("true"); 
        } 
        else { 
            alert("false"); 
        }
    } 
});

http://api.jquery.com/has-selector/

Description: Selects elements which contain at least one element that matches the specified selector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜