简体   繁体   中英

How to disable trigger click after first click

onclick of the a elements I need to call a function and trigger #myDiv only once. Assume I am clicking 'Apple' any number of times it should trigger only one time. Then go to 'Orange' or 'Banana' and come back to 'Apple' again as same as earlier I need to trigger only one time. Assume there can be any number of a and those are dynamic. How can I achieve this?

 function activateMyClick(myId) { $('#myDiv').trigger('click'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a onclick="activateMyClick(7)" id="7" class="active">Apple</a> <a onclick="activateMyClick(8)" id="8" class="active">Orange</a> <a onclick="activateMyClick(9)" id="8" class="active">Banana</a> 

As you've tagged this with jQuery you could remove the outdated on* event attributes and use one() to achieve this:

 $('a.active').one('click', function() { $('#myDiv').trigger('click'); }); // for demonstration purposes only: $('#myDiv').click(function() { console.log('div click raised!'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="7" class="active">Apple</a> <a id="8" class="active">Orange</a> <a id="8" class="active">Banana</a> <div id="myDiv"></div> 

A simple solution but I think works as you describe.

  • Multiple clicks on Apple, trigger fires only one time
  • After clicking on other links and then click again on Apple, trigger fires again only one time

 var currentId = ""; function activateMyClick(myId) { if (currentId != myId) $('#myDiv').trigger('click'); currentId = myId; } $('#myDiv').click(function() { console.log('div click raised!'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a onclick="activateMyClick(7)" id="7" class="active">Apple</a> <a onclick="activateMyClick(8)" id="8" class="active">Orange</a> <a onclick="activateMyClick(9)" id="8" class="active">Banana</a> <div id="myDiv"></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