Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Using multiple buttons on same function that redirects to different functions

So..i'm having this problem for couple of days not knowing how to do this,and i need help.

I have multiple buttons and clicking all of them is redirecting me to same function and from that function is going to another function specified for that button. Any idea how can i go true couple of functions knowing which button is clicked? example :

 <html>

<button type="button" onclick="myFunction()" id="1">Button1</button>
<button type="button" onclick="myFunction()" id="2">Button1</button>
<button type="button" onclick="myFunction()" id="3">Button1</button>

<script>

function myFunction()
{
   var x=0;

    if (button 1){
     x=1;
     myFunction1(x);}

   if (button 2){
    x=2;
    myFunction2(x);}

    if (button 3){
     x=3;
     myFunction3(x);}

     ...
    myFunction3(x){
    alert(x);
}
}

</script>

</html>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Easiest way would probably be to pass in the element into the function:

<button type="button" onclick="myFunction(this)" id="1">Button1</button>
<button type="button" onclick="myFunction(this)" id="2">Button1</button>
<button type="button" onclick="myFunction(this)" id="3">Button1</button>

function myFunction(elem) {
    alert(elem.id);
}

No need to think about event arguments or anything like that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...