【问题标题】:Multiple HTML elements with same ID causing errors具有相同 ID 的多个 HTML 元素导致错误
【发布时间】:2013-10-09 21:43:39
【问题描述】:

我目前遇到了一个问题,在我的 HTML 文档中,我有一个轮播,并且在每张幻灯片中都会显示一个新按钮,所有这些都在做同样的事情。这些按钮中的每一个都是一个导航栏切换按钮,如果按下它就会显示一个导航栏。

我遇到的问题是,在我给出的代码中,它只说明其中一个按钮工作,第一个加载,因为它通过var showRightPush = document.getElementByID 声明变量。问题是我希望能够在每张幻灯片上单击此按钮。

以下是我的代码、旧代码以及完整上下文中的代码。 谢谢。

我的代码

<script>
  var menuRight = document.getElementById( 'cbp-spmenu-s2' ),
    showRightPush = document.getElementsByClassName( 'navbar-toggle' ),
    body = document.body;


  showRightPush.onclick = function() {
    classie.toggle( this, 'active' );
    classie.toggle( body, 'cbp-spmenu-push-toleft' );
    classie.toggle( menuRight, 'cbp-spmenu-open' );
    disableOther( 'navbar-toggle' );
  };


</script>

旧代码

<script>
  var menuRight = document.getElementById( 'cbp-spmenu-s2' ),
    showRightPush = document.getElementById( 'showRightPush' ),
    body = document.body;


  showRightPush.onclick = function() {
    classie.toggle( this, 'active' );
    classie.toggle( body, 'cbp-spmenu-push-toleft' );
    classie.toggle( menuRight, 'cbp-spmenu-open' );
    disableOther( 'showRightPush' );
  };


</script>

完整代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php bloginfo('name'); ?> </title>

    <!-- Bootstrap core CSS -->
    <link href="<?php bloginfo('template_directory'); ?>/css/bootstrap.css" rel="stylesheet">

    <!-- Sidebar core CSS -->
    <link href="<?php bloginfo('template_directory'); ?>/css/simple-sidebar.css" rel="stylesheet">

    <!-- Add custom CSS here -->
    <link href="<?php bloginfo('template_directory'); ?>/style.css" rel="stylesheet">
    <link href="<?php bloginfo('template_directory'); ?>/css/default.css" rel="stylesheet">
    <link href="<?php bloginfo('template_directory'); ?>/css/component.css" rel="stylesheet">

  </head>

<body class="cbp-spmenu-push">

      <nav class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-right" id="cbp-spmenu-s2">
        <h3><?php bloginfo('name'); ?></h3>
        <a href="#">About</a>
        <a href="#">Submit</a>
        <a href="#">Subscribe</a>
        <a href="#">Follow</a>
        <a href="#">Contact</a>
      </nav>


      <?php 
     $number = 0; 
     query_posts(array('post_type' => 'facts')); 
     if(have_posts()):  
    ?>
    <div id="myCarousel" class="carousel slide">
      <ol class="carousel-indicators">
        <?php while(have_posts()): the_post(); ?>
          <li data-target="#myCarousel" data-slide-to="<?php echo $number++; ?>"></li>
        <?php endwhile; ?>
      </ol>

      <!-- Carousel items -->
      <div class="carousel-inner">
        <?php while(have_posts()): the_post(); ?>

        <div class="item">
          <nav class="navbar navbar-top navbar-inverse visible-xs <?php foreach(get_the_category() as $category) {echo $category->slug;} ?>" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" id="showRightPush" class="btn btn-default navbar-toggle" >
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#"><img src="<?php bloginfo('template_directory'); ?>/images/brains.png" alt=""> </a>
            </div> <!-- end navbar-header -->
          </div> <!-- end container -->
          </nav> <!-- end navbar -->

          <nav class="navbar navbar-fixed-bottom navbar-inverse visible-xs bottom-nav-colour" role="navigation">
            <div class="container">
              <div class="navbar-header text-center">
                <ul class="bottom-directions">
                  <li><a href="#myCarousel" class="bottom-arrow-nav" data-slide="prev"><img src="<?php bloginfo('template_directory'); ?>/images/prev.png" alt=""></a></li>
                  <li><a href="#myCarousel" class="bottom-arrow-nav" data-slide="random"><img src="<?php bloginfo('template_directory'); ?>/images/random.png" alt=""></a></li>
                  <li><a href="#myCarousel" class="bottom-arrow-nav no-border-right" data-slide="next"><img src="<?php bloginfo('template_directory'); ?>/images/next.png" alt=""></a></li>
                <ul>
              </div> <!-- end navbar-header -->
            </div><!-- /.container -->
          </nav> <!-- end navbar -->

          <div class="fact-number-container <?php foreach(get_the_category() as $category) {echo $category->slug;} ?>">
            <div class="container">
              <div class="fact-header">
                <h3>/Fact <span class="fact-number"><?php echo(types_render_field("fact-number", array())); ?></span></h3>
              </div> <!-- end fact-header -->
            </div> <!-- end container -->
          </div> <!-- end fact-number-container -->

          <div class="fact-text-container">
            <div class="container">
              <div class="fact-text">
                <p><?php echo(types_render_field("fact-text", array())); ?></p>
              </div> <!-- end fact-text -->
            </div> <!-- end container --> 
          </div> <!-- end fact-text-container -->

          <div class="tweet-this-container">
            <div class="container">
              <a href="#"> 
                <div class="tweet-this ">
                  <p><img src="<?php bloginfo('template_directory'); ?>/images/twitter.png" alt="">Share this fact like a champ</p>
                </div> <!-- end tweet-this -->
              </a> 
            </div> <!-- end container -->
          </div> <!-- end tweet-this-container -->
        </div> <!-- end item -->
        <?php endwhile; ?>
      </div>
    </div>
    <?php endif; wp_reset_query(); ?>



    <!-- Bootstrap core JavaScript -->
    <!-- Placed at the end of the document so the pages load faster -->
    <!-- Make sure to add jQuery - download the most recent version at http://jquery.com/ -->
    <script src="<?php bloginfo('template_directory'); ?>/js/jquery.js"></script>
    <script src="<?php bloginfo('template_directory'); ?>/js/bootstrap.js"></script>
    <script src="<?php bloginfo('template_directory'); ?>/js/classie.js"></script>
    <script src="<?php bloginfo('template_directory'); ?>/js/modernizr.custom.js"></script>
    <script type="text/javascript" src="//use.typekit.net/gyv3ykj.js"></script>
    <script type="text/javascript">try{Typekit.load();}catch(e){}</script>

    <script>
      var menuRight = document.getElementById( 'cbp-spmenu-s2' ),
        showRightPush = document.getElementsByClassName( 'navbar-toggle' ),
        body = document.body;


      showRightPush.onclick = function() {
        classie.toggle( this, 'active' );
        classie.toggle( body, 'cbp-spmenu-push-toleft' );
        classie.toggle( menuRight, 'cbp-spmenu-open' );
        disableOther( 'navbar-toggle' );
      };


    </script>
    <script>
    jQuery(document).ready(function(){
      $(".carousel-indicators li:first").addClass("active");
      $(".carousel-inner .item:first").addClass("active");  
    });
    </script>


  </body>
</html>

【问题讨论】:

  • 这段代码/html你能改变多少?当您拥有不独特的东西时,最好远离 id。
  • “多个具有相同 ID 的 HTML 元素导致错误”,是的。一开始那是无效的 HTML。
  • 是的,我正在尝试更改它的代码以调用类,但它不起作用。这就是我提出这个问题的全部原因。
  • 那么你应该从重命名主题开始,考虑到你做了适当的改变。
  • 如果你使用 jQuery,你可以不用 $('.class-name')

标签: javascript jquery html css twitter-bootstrap


【解决方案1】:
  showRightPush = document.getElementsByClassName( 'navbar-toggle' ),

  showRightPush.onclick = function() {
      /* ... */
  };

天哪,那行不通! 我刚刚回答了这个问题:Javascript change width of div onclick

只会复制粘贴我的答案:

document.getElementsByClassName 返回一个数组 元素,因此您不能简单地将其称为 DOM 元素 它会在您引用集合的每个元素时起作用(即 在 jQuery 中是可能的,顺便说一句),所以你必须使用 foreach 循环 (不管你将如何实现这一点——通过简单的for(), 或for(x in y),或任何其他方式)。

我通常使用Array.forEach函数,但具体类型 document.getElementsByClassName 返回的数组没有 原型中有这样的功能,所以你必须使用 [].forEach.call(inWhat,function(what){}) 语法,或回退到 for(...) 语法。

【讨论】:

    【解决方案2】:

    首先,请注意getElementsByClassName 方法仅适用于 Internet Explorer 9 及更高版本。您可以使用像 this one 这样的 polyfill 来启用旧浏览器中的功能,或者使用其他方法来查找具有正确类名的元素。话虽如此,您必须遍历按钮并为每个按钮绑定点击事件。

    var showRightPush = document.getElementsByClassName( 'navbar-toggle' );
    for (var i = 0; i < showRightPush.length; i++) {
        showRightPush[i].onclick = function() { ... }
    }
    

    【讨论】:

      【解决方案3】:

      我不太明白你的意思,不是很清楚。但据我了解,你应该做这样的事情(我使用jQuery,因为你标记了它)

      $('.navbar-toggle').on('click', function() {
          ...some events
          var class_header = $(this).parent().attr('class');
          var index = $('.'+class_header).indexOf($(this).parent());
          $('.'+class_header).eq(index+1).append('/*whatever you want, here your button */'); 
        };
      

      【讨论】:

        猜你喜欢
        • 2017-06-09
        • 2017-06-13
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        • 1970-01-01
        • 2017-10-15
        相关资源
        最近更新 更多