在jquery中创建div滑块

时间:2018-03-02 12:18:57

标签: javascript jquery

当我点击我正在构建的网站上的一段文字时,我正在尝试更改图像。 此时我创建了一个名为device的类,其中一个设备处于活动状态,如下所示:

  <div class="col-md-3">
        <div class="device active">
          <img src="app/assets/images/mockup.png" alt="">
        </div>
        <div class="device">
          <img src="app/assets/images/mockup.png" alt="">
        </div>
        <div class="device">
          <img src="app/assets/images/mockup.png" alt="">
        </div>

    </div>

然后我正在尝试做的是当我用#search2的i.d点击一些文本时删除活动类。到目前为止,这是我的整个jquery脚本:

$("#search2").click(function() {
  var currentImage = $('.device.active');

  var nextImage = currentImage.next();

  currentImage.removeClass('active');

});

然而,这似乎没有删除活动类,仍然显示图像?有任何想法吗?

2 个答案:

答案 0 :(得分:1)

您的选择是正确的,它适用于我(活动类已从该项目中删除)。问题必须在您的代码中的其他位置。

这是另一种选择:

&#13;
&#13;
var activeDeviceIndex = 0;

$("#search2").click(function() {
	var devicesContainer = $('.device');
	$(devicesContainer[activeDeviceIndex]).removeClass('active');
	activeDeviceIndex === devicesContainer.length - 1 ? activeDeviceIndex = 0 : activeDeviceIndex++;
	$(devicesContainer[activeDeviceIndex]).addClass('active');
});
&#13;
.device {
  display: none;
}

.device.active {
  display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
      <div class="device active">
        <p>Device 1</p>
      </div>
      <div class="device">
        <p>Device 2</p>
      </div>
      <div class="device">
        <p>Device 3</p>
      </div>
  </div>
  
  <button id="search2">click</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

选中以下内容,要点按的按钮上的ID应为search2,而不是#search2,可能只是拼写错误。

之后更新您的代码如下

/**
*@description - gets the next image to slide, if the last image is the current image, it will loop the sliding
*@param {Element} current - the currently active image
*@param {Boolean} islooped - boolean value indicating if a looping just started
*/
var nextImage = function(current, islooped) {
    var next = islooped? current : current.nextSibling;
    while(next && next.nodeName.toLowerCase() !== 'div') {
        next = next.nextSibling;
    }
    next = next? next : nextImage(current.parentNode.firstChild, true);
    return next;
};
$('#search2').bind('click', function(event) {
    var current = $('.device.active').removeClass('active').get(0);
    var next = nextImage(current, false);
    $(next).addClass('active');
});