【问题标题】:How to check if an element exist into another element?如何检查一个元素是否存在于另一个元素中?
【发布时间】:2011-08-24 10:41:28
【问题描述】:

我想,对于 jQuery,了解一个元素是否存在于另一个元素中。

类似的东西:

if($('#container').find('.search_element'))

如果.search_element 进入#container,则必须返回YES,否则返回NO。

我该怎么做?尝试使用 $.contains('#container', '.search_element') 但似乎此功能不起作用...

【问题讨论】:

标签: jquery


【解决方案1】:

简单的长度检查:

if($("#container").find(".search_element").length) {
    // If the length is greater than 0, it exists
} else {
    // else, false
}

【讨论】:

    【解决方案2】:

    ¡¡¡更新!!!

    查看我的回答 [ HERE ] 以获得更多更强大的插件!


    您可以通过以下方式轻松缩短@Chris 的答案:

    if($("#container .search_element").length) { ...
    

    您也可以使用我为此制作的有用插件来做同样的事情:

    jsFiddle

    (function($) {
        if (!$.exist) {
            $.extend({
                exist: function(elm) {
                    if (typeof elm == null) return false;
                    if (typeof elm != "object") elm = $(elm);
                    return elm.length ? true : false;
                }
            });
            $.fn.extend({
                exist: function() {
                    return $.exist($(this));
                }
            });
        }
    })(jQuery);
    

    使用

    //  With your if statement
    if($("#container .search_element").exist()) { ...
    
    //  With ID 
    $.exist("#eleID");
    //  OR
    $("#eleID").exist();
    
    //  With class name
    $.exist(".class-name");
    //  OR
    $(".class-name").exist();
    
    //  With just tag // prolly not best idea aS there will be other tags on site
    $.exist("div");
    //  OR
    $("div").exist();
    

    当然,这个插件还可以进一步扩展,变得更加花哨(一次处理多个调用,基于婴儿车创建不存在的元素),但就目前而言,它做了一个非常简单、非常需要的功能。 ..这个元素存在吗?返回TrueFalse

    jsFiddle

    【讨论】:

    • 提示(我正在考虑这样做,但不确定人们会如何使用它)您可以编辑插件以具有回调函数。那么你根本不需要“if”语句。
    【解决方案3】:

    您可以使用.is:has,只是为了完整。不过,我更喜欢测试 .length 的解决方案。

    if($('#container').is(':has(.search_element)')) {
       // I haz that
    }
    

    【讨论】:

      【解决方案4】:

      检查数组的长度

      if($('#container').find('.search_element').length)
      

      【讨论】:

        【解决方案5】:

        jQuery 有一个默认方法:

        $("#container").has(".selector");
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-06
          • 1970-01-01
          • 2017-08-04
          • 1970-01-01
          • 2016-06-29
          • 2020-12-03
          • 2010-11-20
          • 2019-02-12
          相关资源
          最近更新 更多