javascript - 如何将变量从javascript函数返回到html主体中

标签 javascript html

我还是 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>

然后在 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>

目前函数似乎没有返回任何内容(尽管如果我在函数内部输出变量“chosen”那么它工作正常。

提前致谢!

最佳答案

这里有一个更简单的方法。

首先,对您的 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>

然后将脚本更改为:

<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>

...并将它放在结尾 </body> 内标签。

Click here to test a working example. (jsFiddle)

关于javascript - 如何将变量从javascript函数返回到html主体中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4706960/

相关文章:

javascript - 定义回调并立即触发一次的最佳方式?

html - 响应式网站设计中的重叠元素

javascript - 用于大于 0 的数字的 Angular JS 指令

javascript - 不在 div id 中的所有输入元素上的 JQuery .focusin 事件

javascript - 如何使用 Jquery 编辑元素的样式属性

javascript - 阿拉伯文字显示不正确

javascript - 在 JavaScript Promise 中放置 http get 调用的位置

HTML CSS 取尽可能多的高度

javascript - Div 元素仅出现几秒钟

javascript - 简单的节点与 polymer 的结合