如何将其编写为JavaScript函数?

时间:2010-04-10 18:15:24

标签: javascript xhtml

我将以下代码段嵌入到我的某些div中,因此当点击这些div时会检查某个单选按钮。

onclick="document.g1.city[0].checked=true;"

但是我想将上面的调用转换为如下所示的函数调用:

onclick="checkRadioButton(city[0]);"

该功能将是这样的

function checkRadioButton(input){
    document.g1.input.checked=true;
}

我有办法实现这个目标吗?

2 个答案:

答案 0 :(得分:3)

您可以在onclick属性中编写任何Javascript代码。请记住,city[0]未在任何地方定义。要访问它,您必须指定完整的document.g1.city[0]。因此onclick成为:

onclick="checkRadioButton(document.g1.city[0]);"

在您的函数中,您已经在接收元素,而不必再次从文档中检索它。您可以直接设置它的checked属性:

function checkRadioButton(input) {
   input.checked = true;
}

答案 1 :(得分:0)

onclick="checkRadioButton(document.g1.city[0]);"

checkRadioButton(var input){
    input.checked=true;
}

例如,如果您标记的每个document.g1.city[0]都具有属性“radioID”,并且属性的值必须与给定的ID相匹配,那么您也可以减少提供DIV的需要。单选按钮:

onclick="checkRadioButton(this);"

checkRadioButton(var div){
    document.getElementById(div.radioID).checked=true;
}
相关问题