简体   繁体   English

单击锚元素时触发事件

[英]Triggering event when anchor element is clicked

I have a list like this: 我有一个这样的列表:

<ul class="titles clearfix">

 <li class="opened">Billing Address</li>
 <li class="">Shipping Address</li>
 <li class="">Review Order</li>

</ul>

And a button: 还有一个按钮:

<a href="#">Next</a>

How it's working: 它是如何工作的:

The first list item is opened by default (it has a class of "opened") and if I click on "Shipping address" (only if I click) the class "opened" it's applied to the "Shipping address". 默认情况下打开第一个列表项(它有一个“打开”类)如果我点击“发货地址”(仅当我点击),“打开”类将它应用于“发货地址”。

What I want to do is, when I click on next to open "Shipping address" and If I click again to open "Review Order". 我想要做的是,当我点击旁边打开“送货地址”时,如果我再次点击打开“查看订单”。

Basically, what I need to do is when "next" is clicked to force clicking "Shipping address" for example. 基本上,我需要做的是点击“下一步”以强行点击“送货地址”。

How can I do this? 我怎样才能做到这一点?

You can use addClass() and removeClass() to set the class as needed, and next() to get the following li element. 您可以使用addClass()removeClass()根据需要设置类,然后使用next()获取以下li元素。 Try this: 尝试这个:

$('a').click(function(e) {
    e.preventDefault();    
    $('li.opened').removeClass('opened').next().addClass('opened');
});

If required, you would need to implement some logic to prevent the user going past the third li element. 如果需要,您需要实现一些逻辑以防止用户通过第三个li元素。

Example fiddle 示例小提琴

 var i = 2 ; var len = $("ul li").length; $('a').on('click', function(){ $("ul li.opened").removeClass('opened'); $("ul li:nth-child("+ i +")").addClass('opened'); console.log(i, len); if (i == len) { i = 1; }else{ i++; } }); 
 .opened{ color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <ul class="titles clearfix"> <li class="opened">Billing Address</li> <li class="">Shipping Address</li> <li class="">Review Order</li> </ul> <a href="#">Next</a> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM