Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

javascript - Element that calls the function JS

Could someone say how to select and element that called current function?

function Myfunc() {
  element.style.padding = '16px';
}

//---

<button onclick="Myfunc()">Click Me!</button>

I ask how to do it without giving an id or class to the element, and without:

function Myfunc(this) { }

question from:https://stackoverflow.com/questions/65829193/element-that-calls-the-function-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can explicitly pass the element as the argument of the function, you can refer to the event object, or you can inline the code (this last one is not a good option but it works nonetheless):

function clickFunc1(element) {
  element.style.padding = '16px'
}

function clickFunc2() {
  event.target.style.padding = '16px'
}
<button onclick="clickFunc1(this)">ClickMe 1</button>
<button onclick="clickFunc2()">ClickMe 2</button>
<button onclick="this.style.padding = '16px'">ClickMe 3</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...