【问题标题】:grab active element after button click单击按钮后抓取活动元素
【发布时间】:2020-06-03 22:09:12
【问题描述】:

我在具有以下结构的页面上有轮播:

<div class="my-controls">
  <button class="button123">
    <span class="abc">Next-image</span>
  </button>
</div>

<div class="my-carousel">                        
  <div class="item active">image1</div>                       
  <div class="item">image2</div>
  <div class="item">image3</div>
</div>

点击时同一页面上有一个按钮,我需要抓取 active 元素。

我尝试过这样的事情,但我看到的问题是在触发按钮事件后添加/更改了活动类,因此它没有给我预期的 div 元素:

$( document ).ready(function() {
$(".button123").click(function(){
    var activeElement = $(".my-carousel .active")
    //do something with activeElement
});
});

请告诉我如何在活动元素更改后获取它。

【问题讨论】:

  • 我们需要更多代码。单击按钮是否会执行诸如推进轮播之类的操作?您的代码在什么时候添加/删除活动类?
  • 请添加更多信息
  • 单击按钮推进轮播并将类名添加到活动到适当的轮播。添加了更多信息。
  • 为什么不添加推进轮播等的代码?
  • 我无权访问那部分代码,因为它来自外部库。否则,一旦将类更改为活动状态,我就会在该代码中添加此逻辑。

标签: javascript html jquery


【解决方案1】:

如果我理解正确,您希望在活动类位于该元素上之前访问新的活动元素。因此,您想弄清楚活动类将在哪个元素上。

答案取决于轮播。如果它只是以一种方式遍历所有项目,而不循环,则可以使用 jQuery 的 .next() 方法“保持领先”:

$( document ).ready(function() {
  $(".button123").click(function(){

    if ($(".my-carousel .active").next().length) {
      // There is a next item, set activeElement to it
      var activeElement = $(".my-carousel .active").next()
    }

    // Do something with activeElement
  });
});

如果轮播循环,您可以添加一个else 语句,如果没有.next() 子项,则将轮播重置为第一项:

$( document ).ready(function() {
  $(".button123").click(function(){

    if ($(".my-carousel .active").next().length) {
      // There is a next item, set activeElement to it
      var activeElement = $(".my-carousel .active").next()
    } else {
      // There is no next item, start from the beginning
      var activeElement = $(".my-carousel .active").siblings(":first-child")
    }

    // Do something with activeElement
  });
});

如果轮播也可以双向移动,则您必须连接另一个按钮,即向后滚动的按钮。复制点击函数,将.next()替换为.prev()就可以了!

这是一个用于双向循环和移动的轮播的 CodePen:https://codepen.io/PXJesse/pen/YzwzgQR

【讨论】:

  • 点击同一个按钮会改变活动类。在第一次加载时,我可以抓住活动元素,因为在初始加载时,类已经设置好了。
  • 对不起,我完全误读了你的问题。我更新了我的答案,希望对您有所帮助!不过快速免责声明,我强烈建议您在活动类更改后找到一种运行代码的方法,这样您就可以使用$(".my-carousel .active") 选择它。我上面的回答很实用,但很老套。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 2016-11-16
相关资源
最近更新 更多