简体   繁体   English

从链接中选择单选按钮

[英]Selecting Radio Buttons from Links

I am learning javascript from the "Javascript in 10 steps on less" book. 我正在从“少花10个步骤的Javascript”一书中学习javascript。 On task 90 where the task is selecting radio buttons from the link,i tried the code as exactly in book. 在任务90(该任务正在从链接中选择单选按钮)上,我尝试了完全与本书中的代码相同的方法。 There is the error that "TypeError: document.myForm.myRadio is not a function". 出现“ TypeError: document.myForm.myRadio不是函数”的错误。 My code is as follows: 我的代码如下:

<script language="JavaScript">
function selectButton(button) {
    document.myForm.myRadio(button).checked = true;
}
</script>
<form name="myForm">
    <input type="radio" name="myRadio" value="First Button" /> Button 1<br>
    <input type="radio" name="myRadio" value="Second Button" /> Button 2
</form>
<a href="#" onClick="selectButton(0);">Select First Radio Button</a><br>
<a href="#" onClick="selectButton(1);">Select Second Radio Button</a>

I myself see no error in the code. 我本人认为代码中没有错误。 Anyone help me point out the error. 任何人都可以帮助我指出错误。

There: 那里:

function selectButton(button)...

you are passing button as an argument to the function selectButton . 您正在将button作为参数传递给selectButton函数。 Using () in this case is correct. 在这种情况下使用()是正确的。

But there: 但是那里:

document.myForm.myRadio(button).checked = true;

myRadio is array of buttons. myRadio是按钮数组。 Indexes in arrays are accessed using [] syntax. 使用[]语法访问数组中的索引。

So it should be 所以应该

document.myForm.myRadio[button].checked = true;

Demo: 演示:

 <script language="JavaScript"> function selectButton(button) { document.myForm.myRadio[button].checked = true; } </script> <form name="myForm"> <input type="radio" name="myRadio" value="First Button"> Button 1<br> <input type="radio" name="myRadio" value="Second Button"> Button 2 </form> <a href="#" onClick="selectButton(0);">Select First Radio Button</a><br> <a href="#" onClick="selectButton(1);">Select Second Radio Button</a> 

You code is correct but use [] bracket instead of () like: 您的代码是正确的,但是使用[]括号而不是()例如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
 <script language="JavaScript">
function selectButton(button) {
document.myForm.myRadio[button].checked = true;
}
</script>
<form name="myForm">
<input type="radio" name="myRadio"
value="First Button"> Button 1<br>
<input type="radio" name="myRadio"
value="Second Button"> Button 2
</form>
 <a href="#" onClick="selectButton(0);">Select First
 Radio Button</a><br>
 <a href="#" onClick="selectButton(1);">Select Second
 Radio Button</a>
</body>
</html>

FIDDLE DEMO 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM