-2

我有一个我认为应该是返回 TypeError 的简单函数:ele("XYZ") is null 并且没有返回正确的值。在我的例子中,元素 XYZ 被称为“AgeCount”。这是我的脚本:

function countAgesSelected(){
    var agesSelectedCount = 0;
    if (document.myform.a4049.checked==true) {
         agesSelectedCount++;
    }
    if (document.myform.a5064.checked==true) {
         agesSelectedCount++;
    }
    if (document.myform.a65plus.checked==true) {
         agesSelectedCount++;
    }
    ele('AgeCount').value = agesSelectedCount;
}

浏览器在最后一行抛出错误。

这是相关的HTML:

<input name="4049" type="checkbox" value="4049" id="a4049" starweb_type="Checkbox/Radio Button" checked="checked" onclick="countAgesSelected()" />40-49
<input name="5064" type="checkbox" value="5064" id="a5064" starweb_type="Checkbox/Radio Button" checked="checked" onclick="countAgesSelected()" />50-64
<input name="65plus" type="checkbox" value="65plus" id="a65plus" starweb_type="Checkbox/Radio Button" checked="checked" onclick="countAgesSelected()" />65+
<input type="hidden" value="0" name="AgeCount" />

我希望因为我是一个 JavaScript 新手,所以我只是有一个简单的语法错误。任何帮助是极大的赞赏!

4

2 回答 2

-1
function countAgesSelected(){
    var agesSelectedCount = 0;
    if (document.myform.a4049.checked==true) {
         agesSelectedCount++;
    }
    if (document.myform.a5064.checked==true) {
         agesSelectedCount++;
    }
    if (document.myform.a65plus.checked==true) {
         agesSelectedCount++;
    }
    document.getElementsByName('AgeCount')[0].value = agesSelectedCount;
}

抱歉,将其读取为 ID,而不是名称

于 2012-11-14T17:14:59.817 回答
-1

更新

混合了 getElementsByName 和 getElementsByTagName,代码现已更新。

函数从何ele而来?

使用document.getElementsByName("AgeCount")[0]代替 ele 函数或像这样创建 ele 函数:

function ele(element)
{
    return document.getElementsByName(element)[0];
}
于 2012-11-14T17:16:24.973 回答