自动添加bootsrap轮播控制按钮

时间:2017-02-02 12:12:23

标签: javascript jquery twitter-bootstrap

我写了一个jquery函数来自动添加引导指示器,但我想添加carousel control,就像下面的示例代码一样,carousel-control href必须与carousel id相同,我怎么能这样做? / p>

 <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>

$(document).ready(function() {
  var myCarousels = $(".carousel");
  myCarousels.each(function(index, element) {
    var myCarousel = $("#" + $(element).attr('id'));
    myCarousel.append("<ol class='carousel-indicators'></ol>");
    var indicators = $("#" + $(element).attr('id') + " .carousel-indicators");
    $("#" + $(element).attr('id') + " .carousel-inner").children(".item").each(function(index) {
      (index === 0) ?
      indicators.append("<li data-target='#" + $(element).attr('id') + "' data-slide-to='" + index + "' class='active'></li>"):
        indicators.append("<li data-target='#" + $(element).attr('id') + "' data-slide-to='" + index + "'></li>");
    });
  });

});
body {
  margin: 50px;
}
.carousel {
  width: 900px;
  margin: 10px;
}
.carousel-indicators .active {
  background-color: #faa82b !important;
}
<html lang="en">

<head>
  <meta charset="UTF-8" /><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

</head>

<body>


  <div id="carousel-1" class="carousel slide" data-ride="carousel">

    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img src="http://www.jssor.com/img/home/01.jpg">
      </div>
      <div class="item">
        <img src="http://www.jssor.com/img/home/02.jpg">
      </div>

    </div>

  </div>
  <!-- carousel 1-->


  <div id="carousel-2" class="carousel slide" data-ride="carousel">

    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img src="http://www.jssor.com/img/home/03.jpg">
      </div>
      <div class="item">
        <img src="http://www.jssor.com/img/home/04.jpg">
      </div>

    </div>
  </div>
  <!-- carousel 2-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>

</html>

1 个答案:

答案 0 :(得分:2)

没有魔力。只需将左右控件附加到主旋转木马容器(我使用if (string.IsNullOrWhiteSpace(fields[i])) // (fields[i].Length == 0) { fields[i] = string.Format("{0}-1", Environment.NewLine); } 更改href属性,它与您的指示器非常相似,甚至更容易,您不必检查元素是否首先添加{{1 }。class。

$(element).attr('id')

CODEPEN