简体   繁体   中英

JQuery $.contains method always returning false

I'm having an issue here with this part of JQuery code:

$(".roomblock_slots li").droppable({ activeClass: "drop_here", hoverClass: "hover_here", tolerance: "pointer",
        drop: function (event, ui) {
            var container = $(this);
            if (container.contains(container,"div")) {
                return false;
            }
            return true;
        } });

I'm trying to drop an element into a li element, and I want to check if it contains a div element. The issue is, the function itself always returns false and never goes into "return false;", even if the li contains a div element, like this:

<li class="ui-droppable">
    <div class="ui-draggable">
</li>

How do I fix this issue?

The utility method $.contains does not work as you expect.

http://api.jquery.com/jQuery.contains/

The parameters it takes are: container and contained , and you use it like:

$.contains(container, contained)

Both parameters are supposed to be DOM elements...not jQuery objects or selectors.

So in your case, since you're not looking for a specific element being contained in another specific element, you can't use $.contains - you must use another method.

I would suggest using .find and counting how many match:

if (container.find("div").length > 0) {

}

Of course, if you only want to look at immediate children, use:

if (container.children("div").length > 0) {

}

链接时,您将执行以下操作:

if ( container.has('div') ) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM