简体   繁体   English

为什么我把 this.onclick=' '; 放在 function 运行一次?

[英]Why does the function run once when I put this.onclick=' ';?

<a href="#" onclick="addP(); this.onclick='';">See more</a>    

Why does the function run once when I put this.onclick=' ';?为什么我把 this.onclick=' '; 放在 function 运行一次?

When you clicked the link.当您单击链接时。

  1. It calls addP .它调用addP
  2. It removes onclick handler.它删除了 onclick 处理程序。

Now the actual HTML looks like现在实际的 HTML 看起来像

<a href="#" onclick="addP();">See more</a> 

To fix this remove onclick='' part in the onclick attribute.要解决此问题,请删除 onclick 属性中的onclick=''部分。

 let addP = () => alert('you clicked the link')
 <a href="#" onclick="addP();">See more</a>

I think it's overriding the native method:)我认为它覆盖了本机方法:)

You have to remove this.onclick='';您必须删除this.onclick=''; because when the o'clock event ( addP ) Is over, it removes the the click event handler.因为当 o'clock 事件 ( addP ) 结束时,它会删除 click 事件处理程序。 So there are 2 methods for you:因此,有两种方法适合您:


Method 1方法一
use javascript & html like so:像这样使用 javascript 和 html :

HTML: HTML:

<a href="#" id="seeMore">See more</a>    

Javascript: Javascript:

document.getElementById('seeMore').addEventListener('click', function() {
    addP();
});


Method 2方法二
only using html仅使用 html

<a href="#" onclick="addP();">See more</a>    

暂无
暂无

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

相关问题 为什么onclick函数在onclick上运行,而在我手动调用时却不能运行? - Why does the onclick function run on onclick, but not when I call it manually? 如果多次运行初始化,为什么我的jquery onclick函数会打开和关闭? - Why does my jquery onclick function toggle on and off, if I run initialization more than once? 当我尝试在节点中运行函数时,为什么Onclick =“ function()”显示404? - why does Onclick=“function()” shows up 404 when I am trying to run a function in node? 为什么此功能只能运行一次? - Why does this function only run once? 当我运行 .onclick 时,它运行一次,然后它不再工作 - when i run .onclick, it runs once, and then it doesnt work again 当放入onclick处理程序时,为什么此小书签JS代码不起作用? - Why does this bookmarklet JS code not work when put in an onclick handler? 为什么我的函数在按钮中的onClick事件上只能运行一次? - Why does my function runs only once on onClick event in button? 为什么当引用不存在时,firebase“on”“value”不会运行监听器功能,但“一次”“值”是什么? - Why does firebase “on” “value” not run the listener function when the reference doesn't exist, but “once” “value” does? 为什么我的 onclick 属性在提交时不运行 function? - Why does my onclick property not run the function upon submit? jQuery仅运行一次onclick函数 - jQuery run onclick function only once
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM