【问题标题】:JQuery - If ( $('#products').existOn.(document) ) == true { //do this }JQuery - If ( $('#products').existOn.(document) ) == true { //do this }
【发布时间】:2011-06-07 01:04:57
【问题描述】:

我怎样才能使这个条件分支.. 如果带有 ID 的产品在 HTML 代码中?如果#products 确实存在于实际文档中?

感谢您的回复!

伪 Javascript (JQuery)

If ( $('#products').existOn.(document) ) == true { 
   //do this
}

【问题讨论】:

    标签: javascript jquery html if-statement conditional


    【解决方案1】:

    使用length:

    if ( $('#products').length > 0){ 
       // element is present
    }
    

    【讨论】:

      【解决方案2】:

      如果你想改变 document 部分,你可以这样做:

      if( $(document).find('#products').length > 0 ) {
         // do this
      } 
      

      如果它永远是document,那就足够了

      if( $('#products').length > 0 ) {
         // do this
      }
      

      实现第一个示例的另一种方法是将上下文参数作为第二个参数传递:

      if( $('#products', document).length > 0 ) {
         // do this
      }
      

      注意 context 参数应该是一个 DOM 节点,而不是一个 jQuery 对象。

      【讨论】:

        【解决方案3】:

        为什么要使用 jQuery?

        if (document.getElementById('products')) {
          //do this
        }
        

        【讨论】:

        • 正如“为什么选择 jQuery”问题的答案一样:为了跨浏览器的一致性。给定<input name="products" />,您的条件将在 IE6 中生成一个对象,在大多数浏览器中生成null
        • 这真的是评论,而不是问题的答案。请使用“添加评论”为作者留下反馈。
        • @Matthieu - 我不同意。作者问如何识别文档中是否存在具有给定 ID 的元素,我给了他一个解决方案(尽管它也会在 IE6/7 中检测具有该名称的项目)。
        猜你喜欢
        • 2021-10-04
        • 2021-11-05
        • 2022-12-01
        • 2011-09-17
        • 1970-01-01
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        • 2015-02-06
        相关资源
        最近更新 更多