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

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

  • if you want to call more than one function you can use like this: onclick="one();tow();three();" – Bhanu Pratap Dec 03 '21 at 04:42
  • 2
    Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. `HTMLElement.prototype.onclick` should also not be used. Use the `once` property in `addEventListener` instead or use `removeEventListener`. – Sebastian Simon Dec 03 '21 at 05:20

2 Answers2

3

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>    
Ksengine
  • 61
  • 5
0

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>