代码之家  ›  专栏  ›  技术社区  ›  Sungguk Lim

在jquery中按ID选择

  •  0
  • Sungguk Lim  · 技术社区  · 15 年前

    正如你所知道的

    $("#ID")  
    

    返回具有ID的元素。

    但即使没有元素,此代码也始终返回。

    alert($("#htrBuyerCouponNotice"));
    alert(document.getElementById("htrBuyerConponNotice"));
    

    在这种情况下。

    这两条线的结果是不同的。

    我想检查是否有元素 htrBuyerCouponNotice .

    document.getElementByID 如果没有元素,则返回空。

    4 回复  |  直到 15 年前
        1
  •  3
  •   Christian C. Salvadó    15 年前

    你可以查一下 length jquery对象的属性,用于确定匹配元素的数目,例如:

    alert($(selector).length);
    

    你可以直接用在 if 声明,例如:

    var $el = $(selector);
    
    if ($el.length) { // only 0 will coerce to false
      // ...
    }
    

    但大多数时候,您实际上不需要知道选择器是否匹配元素,因为jquery内置方法将被简单地忽略,例如:

    $('#nonExistent').hide();
    

    即使找不到元素,上述语句也不会导致任何错误。

    jquery还具有 size 方法,但我建议您使用 长度 因为它是公共可访问的, 大小 方法的速度稍慢,因为它只是一个返回 长度 财产。

        2
  •  1
  •   Ken    15 年前

    因为jquery返回选定元素的列表,所以如果没有元素,您仍然会得到一个返回——它只是一个空列表。

    检查$(someid')。长度-如果我记得正确的话应该有效。

        3
  •  1
  •   Andrew    15 年前

    选择元素时,jquery将始终返回匹配元素的数组。在你的情况下, $('#htrBuyerCouponNotice') 可能正在返回空数组。相反,检查 $('#htrBuyerCouponNotice').length .

    安得烈

        4
  •  0
  •   Dean Harding    15 年前

    尝试:

    $("#htrBuyerCouponNotice").size()
    

    如果没有具有该标识符的节点,则为零;如果有,则为1。