简体   繁体   中英

click element when another is clicked

I have this list:

<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>

What I want to do is, when I click on "Next" to simulate a click on "Shipping address" and If I click again to simulate a click on "Review Order".

I have tried this:

    jQuery("a.next-checkout").click(function(){
     jQuery("ul.titles li").click().next(); 
    return false;
    });

But when I click it goest straight to the last one from the list and I want to go one by one.

Any ideas how can I do this?

如果您尝试“模拟”点击,则.trigger()方法应该可以使用。

$('#your-selector').trigger('click');

Try this:

This is doing what you exactly need.

$('a.next-checkout').on('click', function () {
    $('.titles li.opened').next().trigger('click');
    return false;
});

This snippet amplifies repetitive click event.

$('a.next-checkout').on('click', function () {
    var nextLi = $('.titles li.opened').next().length ? $('.titles li.opened').next() : $('.titles li:first');
    $('.titles').find(nextLi).trigger('click');
    return false;
});

Demo

A simple answer to your question. - Click on "Next" to simulate a click on "Shipping address" and If I click again to simulate a click on "Review Order".

<ul class="titles clearfix">

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

</ul>

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


var i = 0;
$("a").click(function(){

  if(i == 0)$("li.r").trigger("click");
  if(i == 1)$("li.s").trigger("click");
  i++;
});

$("li").click(function(){ console.log($(this).text() + " clicked")});

fiddle

To get about this kind of a scenario, apart for triggering the click for the li element, you will also need to keep a track of the currently selected li. Below code may e helpful:

var curr;
var first_li=$('li:first', 'ul');;

$("#next").click(function () {

if(!curr)
{
    curr=first_li;
}
else
{
  curr=curr.next('li').length ? curr.next('li') : first_li;
}
curr.trigger('click');
});


$('li').click(function(){
    alert($(this).text());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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