【问题标题】:Javascript / Jquery check if id already existsJavascript / Jquery检查id是否已经存在
【发布时间】:2016-12-04 03:01:59
【问题描述】:

如何检查具有唯一 id 的 html 标签是否存在两次或更多次?

我的伪代码:

if($('#myId') > 1) {
  // exists twice
}

【问题讨论】:

    标签: javascript jquery html exists


    【解决方案1】:

    这太简单了,你可能会从小搜索中得到

    if($("#" + name).length > 1) {
      // if exists twice 
    }
    

    多少次了exists = $("#" + name).length

    【讨论】:

    • 处于有效状态。
    • 在有效条件下——表示条件匹配
    • 根据提问者的需要不匹配的问题。
    【解决方案2】:

    jQuery

    ​​>
    if($("[id=someId]").length > 1) {
        //Do Something
    }
    

    if($("[id=someId]").size() > 1) {
        //Do Something
    }
    

    Javascript

    if(document.querySelectorAll("[id=someId]").length > 1) {
        //Do Something
    }
    

    【讨论】:

      【解决方案3】:

      ID selector 只捕获页面中的第一个元素。所以ID selector的长度应该是0或者1

      所以请改用attribute equals selector 并检查它的长度。

      if($('[id="myId"]').length > 1) {
        // exists twice
      }
      

      if ($('[id="myId"]').length > 1) {
        console.log('twice');
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="myId"></div>
      <div id="myId"></div>

      【讨论】:

      • @JohnDoe2 :很高兴为您提供帮助
      【解决方案4】:
      if($("[id='myId']").length > 1) {
          // write your code here
      }
      

      【讨论】:

        猜你喜欢
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 2019-09-24
        • 2016-03-29
        • 2021-02-12
        • 2012-05-13
        相关资源
        最近更新 更多