jquery - 按上一个和下一个按钮时模拟单击元素列表中的元素

标签 jquery html

我需要创建一个 jQuery 脚本,模拟从元素列表中单击另一个元素,每次按下 next 按钮时,都会单击列表中的下一个元素,每次按下 previous 按钮时,都会单击上一个元素单击列表中的元素。

这是部分有效的代码,但只点击一次

$('#next').click(function() {
  $('li a').trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <span>
    <span>
    <a href="#" class="current">image</a>
    </span>
    </span>
  </li>
  <li>
    <span>
    <span>
    <a href="#" class="">image</a>
    </span>
    </span>
  </li>
  <li>
    <span>
    <span>
    <a href="#" class="">image</a>
    </span>
    </span>
  </li>
</ul>
<div id="prev">prev</div>
<div id="next">next</div>

简而言之,当我按下“下一个”按钮时,我想模拟在类“当前”的元素之后单击标签,但是当我按下“上一个”按钮时,我想模拟在之前的标签上单击具有“当前”类的元素。

可悲的是,跨度对于这种布局是必要的,如果它们不存在,我很可能使用 .next() 函数,正如我在类似的堆栈帖子中看到的那样,但因为在我的情况下元素不是直接定位的一次又一次,这个功能不起作用,或者我无法让它起作用。

谢谢!

最佳答案

根据@Taplar 的评论创建答案。

此代码示例基于当前类的 a 上一个/下一个进度。 它找到最近的 li,然后转到下一个(或上一个)并触发点击。

closest(): Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree

$('#next').click(function() {
  var $next = $('a.current').closest('li').next().find("a");
  $next = $next.length > 0 ? $next : $("ul li:first-child a"); //if the end get the first one.
  $next.trigger('click');
});
$('#prev').click(function() {
  var $prev = $('a.current').closest('li').prev().find("a");
  $prev = $prev.length > 0 ? $prev : $("ul li:last-child a"); //if the start get the last one.
  $prev.trigger('click');
});
//sample "click" event to toggle the current class
$("li a").click(function(e) {
  e.preventDefault();
  $("li a").removeClass("current");
  $(this).addClass("current");
});
.current {
  background-color: orange;
}

div[id] {
  border: 1px solid #ccc;
  border-radius: 10px;
  height: 20px;
  width: 50px;
  display: inline-block;
  text-align: center;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <span>
    <span>
    <a href="#" class="current">image</a>
    </span>
    </span>
  </li>
  <li>
    <span>
    <span>
    <a href="#" class="">image</a>
    </span>
    </span>
  </li>
  <li>
    <span>
    <span>
    <a href="#" class="">image</a>
    </span>
    </span>
  </li>
</ul>
<div id="prev">prev</div>
<div id="next">next</div>

关于jquery - 按上一个和下一个按钮时模拟单击元素列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55285332/

相关文章:

jquery mobile - JS 未在多 HTML 应用程序的第二页上执行

html - 在页面重定向上保持按钮状态

javascript - 提交时显示表单输入

jquery - OnClick,显示div,然后跳转到正确的位置

c# - 使用 <ul> 进行导航(无法记住状态)

html - 使用 float 时如何放置div中心

html - Bootstrap 固定导航在滚动时跳转

android - 寻找 iScroll 的替代品(iOS/Webkit 上的滚动 Div)

javascript - 为什么在jsfiddle中显示ReferenceError : function is not defined?

Jquery - jcarousel 中的错误