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.
精彩评论