我必须点击一个html按钮TWICE来实现我在我的项目中所需要的东西。所以我使用javascript点击按钮使用click()。但是以下脚本对我不起作用。请在此处http://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb试试。
<!DOCTYPE html>
<html>
<body>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
<script>document.getElementById('myImage').click();
document.getElementById('myImage').click();
</script>
</body>
<script>
function changeImage() {
alert(100);
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
</html>
我尝试过只点击一次,看看我是否朝着正确的方向前进,即使这样做不起作用。
答案 0 :(得分:1)
试试这个:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
<script>
// --> Script code should be before closing body tag
function changeImage() {
alert(100);
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
document.getElementById('myImage').click();
</script>
</body>
</html>