HTML在javascript运行后恢复为默认值 [英] html javascript reverts to default after javascript has run

查看:101
本文介绍了HTML在javascript运行后恢复为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习javascript,并且我们已经被赋予了通过点击按钮来改变段落的图像/颜色的任务。我的代码有效,但我必须添加一个alert()来阻止它显示它,因为它一运行就会恢复为默认图像/颜色。

I am learning javascript and we have been given the task of changing image / colour of paragraph from the click of the button. My code works but I had to add an alert() to stop it to show this as it reverts to default image/colour as soon as it runs.

function changeImage() {
    var myTag=document.getElementById("imageColour");
    myTag.src = "images/white.jpg";
    var x = document.getElementById("demo");
    x.style.color = "red";
    // Had to add this to see change
    alert("Has reached changeImage()");
}

<html lang="en">
    <head>
	<meta charset="utf-8"/>
	<script type="text/javascript" src="script.js"></script>
	<title>Exercise 3</title>
    </head>
    <body>
	<h3>Exercise 3</h3>
	<img src="images/black.jpg" id="imageColour"/>
	<form>
	    <button type="submit" id="mySubmitButton">Change Colour</button>
	</form>
	<p id="demo">Click the button to change the colour of this paragraph.</p>
    </body>
</html>
<!--javascript-->
<script type="text/javascript">
    document.getElementById("mySubmitButton").addEventListener("click", changeImage);
</script>

任何帮助表示赞赏。

Any help appreciated.

推荐答案

您正在提交表单。这会导致页面重新加载并重置。

You are submitting a form. That causes the page to be reloaded and reset.

使用 type =button在你处理的时候完全删除表单),或者在事件对象上调用 preventDefault (第一个参数为 changeImage ) 。

Use type="button" (and you might as well remove the form entirely while you are at it) or call preventDefault on the event object (the first argument to changeImage).

这篇关于HTML在javascript运行后恢复为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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