我正在尝试使用外部JavaScript禁用按钮 - 通过提交按钮激活
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Join Email List</title>
<link rel="stylesheet" href="Radio_Button.css">
<script src="Radio_Button.js"></script>
</head>
<body>
<section>
<h1>Fun with Radio Buttonst</h1>
<form id="email_form" name="email_form" method="get">
<input type="radio" name="food1" id="cake1" value="cake" > Cake <br>
<input type="radio" name= "food2"id="muffns1"value="muffins" > Muffins <br>
<input type="radio" name= "food3"id="donuts1" value="donuts1" > hello <br>
<input type="radio" name="food4" id="food1" value="cookies" > Cookies<br>
<input type="submit" id="drink_selection" value="Process Drink Selection" onclick = "join_list()">
<br>
</form>
</section>
</body>
</html>
我的JavaScript如下
var getsElement = function (id) {
return document.getElementById(id);
};
var join_list = function () {
getsElement("cake1").disabled = true;
getsElement("cake1").parentElement.disabled = true;
};
我可以看到按钮在我观看代码时禁用,但当HTML重新出现以供用户访问时,按钮不会被禁用。
答案 0 :(得分:4)
您的按钮重新加载页面,因此您的JS丢失了。此外,您应该更改var join_list(范围var问题,如果您在其他函数中使用此var,例如window.onload
)来运行。
所以你的代码应该是
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Join Email List</title>
<link rel="stylesheet" href="Radio_Button.css">
<script src="Radio_Button.js"></script>
</head>
<body>
<section>
<h1>Fun with Radio Buttonst</h1>
<input type="radio" name="food1" id="cake1" value="cake"> Cake
<br>
<input type="radio" name="food2" id="muffns1" value="muffins"> Muffins
<br>
<input type="radio" name="food3" id="donuts1" value="donuts1"> hello
<br>
<input type="radio" name="food4" id="food1" value="cookies"> Cookies
<br>
<input type="submit" id="drink_selection" value="Process Drink Selection" onclick="join_list()">
</section>
</body>
</html>
的JavaScript
var getsElement = function(id) {
return document.getElementById(id);
};
function join_list() {
getsElement("cake1").disabled = true;
getsElement("cake1").parentElement.disabled = true;
};
答案 1 :(得分:2)
单击“提交”后,页面将重新加载。在页面重新加载之前通过JS添加的任何属性都将设置回默认值。