Javascript / html中的多个onclick事件 [英] Multiple onclick events in Javascript/html

查看:120
本文介绍了Javascript / html中的多个onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为我的html按钮创建多个onclick事件?我现在的代码只能实现一个按钮。我怎样才能让脚本在单击其他按钮时将图像src更改为不同的图像。我尝试了为每个按钮使用不同的功能,但没有奏效。

*

 <身体GT; 
< button class =buttononclick =myFunction()>< strong>目标< / strong>< /按钮>
< button class =button>< strong> Mission Mission< / button>< / strong>
< button class =button>< strong> Chemistry Vision< / strong>< / button>
< button class =button>< strong> Environment Vision< / strong>< / button>< / br>
< img id =myImgsrc =http://image.png>
< script>
函数myFunction(){
document.getElementById(myImg)。src =http:Objectives.png;
}
< / script>
< / body>

*

解决方案您应该将参数传递给函数,如下所示:

 < body> 
< button class =buttononclick =myFunction('Objectives')>< strong>目标< / strong>< / button>
< button class =buttononclick =myFunction('Mission')>< strong> Mission< / button>< / strong>
< button class =buttononclick =myFunction('Chemistry]>< strong> Chemistry Vision< / strong>< / button>
< button class =buttononclick =myFunction('Environment')>< strong> Environment Vision< / strong>< / button>< / br>
< img id =myImgsrc =http://image.png>
< script>
函数myFunction(imgName){
document.getElementById(myImg)。src =http:+ imgName +.png;
}
< / script>
< / body>


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>

*

解决方案

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>

这篇关于Javascript / html中的多个onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆