我必须单击 html 按钮两次才能实现我的项目中所需的内容。所以我使用 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>
我尝试仅单击一次,看看我是否朝着正确的方向前进,即使这不起作用。
最佳答案
试试这个:
<!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>
关于javascript - 使用 javascript 单击 html 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26483210/