getElementById、单选按钮和document.write();

getElementById, radio buttons, and document.write();

本文关键字:write document 单选按钮 getElementById      更新时间:2023-09-26

单选按钮和JS烂透了。好了,现在我把它从我的系统中取出来了这里是我的问题:我终于让Javascript在读取getElementById不与单选按钮玩得很好之后承认了单选按钮的值

我可以警告值但是document.write();不工作吗?

下面是我的代码:
<html>
<head>
<script type="text/javascript">
function getRadioValue() {
var y=document.getElementById('draftrequirement_2').value;
document.write(y);
return y;
}
window.onload = function() { alert(getRadioValue()); }
</script>
</head>
<body>
<input onchange="checkRadio()" type="radio" name="draftrequirement" value="na" id="draftrequirement_2" />
</body>
</html>

在Firefox 5和Chrome 12中,我在警报和文档中都看到了'na',因此document.write()似乎在这些浏览器中工作。但是,在窗口加载事件之后,无线电输入不存在。

我可以问你为什么要使用document.write()吗?操作DOM有许多替代方法。来自w3schools.com (http://www.w3schools.com/js/js_howto.asp)

注意:尽量避免在实际的JavaScript代码中使用document.write()。如果document.write()在函数中使用,或者在页面加载之后,整个HTML页面将被覆盖。然而,document.write()是在教程中演示JavaScript输出的一种简单方法。

不要使用document.write()。!

让你的生活更轻松,开始使用jQuery或类似的库来操作DOM。

如果你只需要使用纯javascript,这应该可以工作:

<html>
<head>
<script type="text/javascript">
function checkRadio() {
var y=document.getElementById('draftrequirement_2').value;
document.getElementById('draftrequirement_2_message').innerHTML = y;
}
</script>
</head>
<body>
<input onchange="checkRadio()" type="radio" name="draftrequirement" value="na"   id="draftrequirement_2" />
<div id="draftrequirement_2_message" />
</body>
</html>
<html> 
<head>
<script type="text/javascript">
function checkRadio() {
var y=document.getElementById('draftrequirement_2').value;
document.write(y);
return y;
}

</script>
</head>
<body>
<input onchange="checkRadio()" type="radio" name="draftrequirement" value="na"     id="draftrequirement_2" />NA
</body>
</html>

使用这个