简体   繁体   中英

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=' ';?

When you clicked the link.

  1. It calls addP .
  2. It removes onclick handler.

Now the actual HTML looks like

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

To fix this remove onclick='' part in the onclick attribute.

 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=''; because when the o'clock event ( addP ) Is over, it removes the the click event handler. So there are 2 methods for you:


Method 1
use javascript & html like so:

HTML:

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

Javascript:

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


Method 2
only using html

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

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