简体   繁体   中英

Click Actions works on second click

This code works properly on first click. When repeated its works only on second click on same element. HTML

<div id="monthly-table">
<a href="#" class="monthly active">Monthly</a>
<a href="#" onclick="subscriptionTable(this)" class="yearly">Yearly</a>
<h1>Monthly</h1></div><div id="yearly-table" style="display:none">
<a href="#" onclick="subscriptionTable(this)" class="monthly">Monthly</a>
<a href="#" class="yearly active">Yearly</a>
<h1>Yearly</h1></div>

SCRIPT

function subscriptionTable(el) {
   $(el).on('click', function() {
       if ($('#yearly-table').is(':hidden')) {
          $('#yearly-table').show();
          $('#monthly-table').hide();
        } else {
         $('#yearly-table').hide();
         $('#monthly-table').show();
       }
      return false;
   });
};

Instead of using the inline click handler to register the jQuery click handler, use jQuery dom ready handler to register the click handler

 jQuery(function($) { $('.period').on('click', function() { var $target = $($(this).attr('href')).show(); $('.target').not($target).hide(); return false; }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="monthly-table" class="target"> <a href="#" class="monthly active">Monthly</a> <a href="#yearly-table" class="yearly period">Yearly</a> <h1>Monthly</h1> </div> <div id="yearly-table" class="target" style="display:none"> <a href="#monthly-table" class="monthly period">Monthly</a> <a href="#" class="yearly active">Yearly</a> <h1>Yearly</h1> </div> 

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