【问题标题】:How to check if an object with an ID already exists on the page? [duplicate]如何检查页面上是否已存在具有 ID 的对象? [复制]
【发布时间】:2011-08-28 12:20:55
【问题描述】:

可能重复:
Is there an “exists” function for jQuery

比如说你有 div:

<div id="hello"></div>

你正在动态创建一个 div:

<div id="hello"></div>

您是否可以在 Jquery 中使用一个函数来检查页面上是否已经存在具有您尝试创建的 ID 的对象?

【问题讨论】:

    标签: jquery jquery-selectors javascript


    【解决方案1】:

    对于 jQuery 方法,您可以使用

    if($("#selector").length) {
        //object already exists
    }
    

    【讨论】:

    • 简单,很棒。这很好用
    【解决方案2】:
    if (document.getElementById('hello')) {
        // yup, already there
    }
    

    或者,jQuery方式:

    if ($('#hello').length) {
        // yup, already there
    }
    

    【讨论】:

    • 太棒了。我会接受的。
    • 更短:($('#hello')[0])
    • 如果您在将它们添加到页面之前创建多个元素,您可以通过此检查为它们提供相同的 id。一个元素可以有一个 id,但在它成为文档的一部分之前,它不会被 document.getElementById 找到。
    • +1 很高兴看到这里提到的两个选项
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 2017-01-09
    • 2021-05-19
    • 1970-01-01
    • 2019-09-09
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多