Multiple onclick events in Javascript/html

2019-09-06 07:10发布

问题:

How can I create multiple onclick events for my html buttons? The code I have right now only implements it for one button. How can I get the script to change the image src to different images when the other buttons are clicked. I tried using different functions for each button but that didn't work.

*

<body>
<button class="button" onclick="myFunction()" ><strong>Objectives</strong></button>
<button class="button"><strong>Mission</button></strong>
<button class="button"><strong>Chemistry Vision</strong></button>
<button class="button"><strong>Environment Vision</strong></button></br>
<img id="myImg" src="http://image.png" >
<script>
function myFunction() {
    document.getElementById("myImg").src = "http:Objectives.png"; 
}
</script>
</body>

*

回答1:

You should pass parameter to the function, something like this:

<body>
<button class="button" onclick="myFunction('Objectives')" ><strong>Objectives</strong></button>
<button class="button" onclick="myFunction('Mission')"><strong>Mission</button></strong>
<button class="button" onclick="myFunction('Chemistry)"><strong>Chemistry Vision</strong></button>
<button class="button" onclick="myFunction('Environment')"><strong>Environment Vision</strong></button></br>
<img id="myImg" src="http://image.png" >
<script>
function myFunction(imgName) {
    document.getElementById("myImg").src = "http:" + imgName + ".png"; 
}
</script>
</body>