简体   繁体   中英

Attribute onclick triggers click event automatically

When I set onclick attribute using jquery , the method is getting called. This is happening only if I use tab key to trigger the link. When I click on the link, no issue occurs. Is this known bug? Please find the code snippet below. However I am not able to reproduce the issue in it and my code is exactly the same.

FYI, I am using jquery 3.1.1.

 function setDeleteLogo() { $('#deleteLogoBtn').attr('onclick', $('#confirmLink').attr('data-onclick')); } function deleteLogo() { alert(); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <a id="confirmLink" onclick="setDeleteLogo()" href="javascript:;" data-onclick="deleteLogo()">Confirm</a> <button id="deleteLogoBtn">Yes, Delete</button> 

.attr is used to enable/disable attributes of a particular element. for eg ('#button').attr('disabled','disabled') where first parameter is atrribute name and second parameter is the value we want to set. Please try using yourElement.click(function() { .... })

I've reworked your example a bit:

  • The button receives a click handler that determines what is called.
  • The confirmation link receives a click handler on first visit.
  • This click handler of the link triggers a click event on the button.
  • The link holds a data attribute ( data-confirmed ) whose presence indicates that is has been visited.

You may want additional logic to have a dynamic call target instead of hard-coded deleteLogo and reset the status of the confirmation link.

 function setDeleteLogo() { if (!$('#confirmLink').attr('data-confirmed')) { $('#confirmLink').on('click', () => { $("#deleteLogoBtn").trigger("click"); 1; }); $('#confirmLink').attr('data-confirmed', '1'); } } function deleteLogo() { alert(); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <a id="confirmLink" onclick="setDeleteLogo()" href="javascript:;">Confirm</a> <button id="deleteLogoBtn" onclick="deleteLogo()" data-onclick="deleteLogo()">Yes, Delete</button> 

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