1

I have a jQuery Mobile Navbar with two tabs:

<div data-role="navbar">
  <ul>
    <li><a href="#" class="tab ui-btn-active">Inbound</a></li>
    <li><a href="#" class="tab">Outbound</a></li>
  </ul>
</div>

When a tab is clicked, I want to

  • do nothing if it's already the active tab,
  • do something if the tab clicked becomes the new active one.

According to the documentation, the active tab has class ui-btn-active, so I listen for clicks and see if that class is present on the clicked button:

$('.tab').click(function() {

  if ( $(this).hasClass('ui-btn-active') ) {
    // already active, do nothing
    console.log("already active");
  } else {
    // newly active, do something
    console.log("newly active");
  }
});

This has worked perfectly for months, but I see now that it is entirely dependent on the timing of when the active class is removed from one and added to the other, relative to when the if is evaluated. Now, after some unrelated code changes, it works as before on desktop browsers, but on mobile browsers, I only get already active, regardless of which button is clicked — i.e. the if happens too late.

What is the smartest way to do this? Can someone explain the sequence of events, and how the inconsistent ordering of events can happen? Is click the right listener to be using for touchscreen devices?

EDIT:

I tried listening for the bubbled event on the parent using .on() and inspecting the event object, hoping the class list it contains would be more accurate, but the behavior is the same:

$('ul').on('click','a',function(event) {
  alert(event.currentTarget.classList.contains('ui-btn-active'));
});

clicking on the inactive tab returns false on desktop browsers, as hoped, and true on mobile browsers.

4

3 に答える 3

1

私見clickはこの目的にはまったく問題なく、変数を使用してアクティブなタブを追跡するだけです。ここにjsFiddleがあります

于 2013-01-02T08:20:12.133 に答える