我仍然是javascript的新手,我正在尝试使用html和javascript返回一个变量的函数.基本上该功能应该只返回用户点击的任何单选按钮,尽管目前我根本没有看到任何返回.
功能在这里:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
Run Code Online (Sandbox Code Playgroud)
然后在html部分我有这些单选按钮,我尝试将变量"选择"输出到屏幕.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
Run Code Online (Sandbox Code Playgroud)
目前似乎没有从函数返回任何东西(尽管如果我在函数内输出变量'selected',那么它正在正常工作.
提前致谢!
这是一个更简单的方法.
首先,对HTML进行一些更正,并创建一个容器来显示输出:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)
然后将脚本更改为:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
Run Code Online (Sandbox Code Playgroud)
...并将其放在结束</body>标记内.
| 归档时间: |
|
| 查看次数: |
80479 次 |
| 最近记录: |