javascript - 在单击表单按钮后应用时,HTML 样式更改不会保留

标签 javascript html

我正在学习 html 的初学者类(class)。通过javascript,我试图在提交表单时修改表单按钮方面,但该修改会立即恢复。看起来 DOM 或表单被重置了,但我不知道如何解决这个问题。

function validateQuestion1(radio){
	document.getElementById("valider1").style.background='green';
	myAnswer = false;
	for (var i=0;i<radio.length;i++) {
		if ((radio[i].checked) && (radio[i].value=="1")) {
			myAnswer=true;				
		}	
	}
}
    <body>
    	<form name="question1">
			<legend>La première balise présente dans un fichier html doit être:</legend>
			<input type="radio" id="choix1" name="Q1" value="0">
			<label for="head" id="head1">head</label>
			<input type="radio" id="choix2" name="Q1" value="0">
			<label for="body" id="head2">body</label>
			<input type="radio" id="choix3" name="Q1" value="1">
			<label for="!DOCTYPE" id="head3">!DOCTYPE</label>
			<input type="radio" id="choix4" name="Q1" value="0">
			<label for="html" id="head4">html</label>
			<button onclick="validateQuestion1(document.forms.question1.Q1)" id="valider1">Valider</button>
    	</form>
   </body>

最佳答案

你可以阻止表单提交

<form onsubmit="return false;">

这将阻止页面刷新。见下文:

function validateQuestion1(radio){
    document.getElementById("valider1").style.background='green';
    myAnswer = false;
    for (var i=0;i<radio.length;i++) {
        if ((radio[i].checked) && (radio[i].value=="1")) {
            myAnswer=true;				
        }	
    }
}
<body>
    <form name="question1" onsubmit="return false;">
        <legend>La première balise présente dans un fichier html doit être:</legend>
        <input type="radio" id="choix1" name="Q1" value="0">
        <label for="head" id="head1">head</label>
        <input type="radio" id="choix2" name="Q1" value="0">
        <label for="body" id="head2">body</label>
        <input type="radio" id="choix3" name="Q1" value="1">
        <label for="!DOCTYPE" id="head3">!DOCTYPE</label>
        <input type="radio" id="choix4" name="Q1" value="0">
        <label for="html" id="head4">html</label>
        <button onclick="validateQuestion1(document.forms.question1.Q1)" id="valider1">Valider</button>
    </form>
</body>

关于javascript - 在单击表单按钮后应用时,HTML 样式更改不会保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57399035/

相关文章:

html - 由于高度 :100%,页脚位置错误

javascript - 标签和内部标签的工具提示

JavaScript/PowerShell : Compare Two files and Save Results to a Text File

javascript - 为什么带有 'undefined' 的表达式不返回 bool 值

javascript对象文字和自执行函数

javascript - JS : Show/hide text field depending on radio button issue

javascript - 删除值后重用 javascript 对象

javascript - Switchery(单选按钮)值到数据库

javascript - 清理数据以防止 XSS

javascript - 使用 jquery 隐藏电子邮件