简体   繁体   English

属性onclick自动触发点击事件

[英]Attribute onclick triggers click event automatically

When I set onclick attribute using jquery , the method is getting called. 当我使用jquery设置onclick属性时,该方法将被调用。 This is happening only if I use tab key to trigger the link. 仅当我使用Tab键触发链接时,才会发生这种情况。 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. 仅供参考,我正在使用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. .attr用于启用/禁用特定元素的属性。 for eg ('#button').attr('disabled','disabled') where first parameter is atrribute name and second parameter is the value we want to set. 例如('#button')。attr('disabled,'disabled')其中第一个参数是属性名称,第二个参数是我们要设置的值。 Please try using yourElement.click(function() { .... }) 请尝试使用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. 该链接包含一个数据属性( data-confirmed ),该属性的存在指示已被访问。

You may want additional logic to have a dynamic call target instead of hard-coded deleteLogo and reset the status of the confirmation link. 您可能希望其他逻辑具有动态调用目标,而不是硬编码的deleteLogo并重置确认链接的状态。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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