Javascript无法找到元素ID

时间:2017-09-02 10:40:40

标签: javascript asp.net

我在javascript文件中使用了javascript函数,因为此函数使用了我的大部分页面。

function setSecondaryItem() {
var select = document.getElementById("<%= SecondaryArea.ClientID %>");
var len = select.length;
...
...}

我也把它放在我的页面中

 <script type="text/javascript" src="../NormalUseFuction.js"></script>

我在下拉列表更改时调用此函数

<asp:DropDownList runat="server" ID="PrimaryArea" onchange="setSecondaryItem()" >
    <asp:ListItem Value="" Text="select..." Selected="True"></asp:ListItem>
    <asp:ListItem Value="A" Text="A.."></asp:ListItem>
    <asp:ListItem Value="B" Text="B.."></asp:ListItem>
    <asp:ListItem Value="D" Text="D.."></asp:ListItem>
    <asp:ListItem Value="E" Text="E.."></asp:ListItem>
    <asp:ListItem Value="F" Text="F.."></asp:ListItem>
    </asp:DropDownList>
<asp:DropDownList runat="server" ID="SecondaryArea" >
    <asp:ListItem Value="1" Text="1.."></asp:ListItem>
    <asp:ListItem Value="2" Text="2.."></asp:ListItem>
    <asp:ListItem Value="3" Text="3.."></asp:ListItem>
    <asp:ListItem Value="4" Text="4.."></asp:ListItem>
    <asp:ListItem Value="5" Text="5.."></asp:ListItem>
</asp:DropDownList>

但是我发现这会出错:未捕获的TypeError:无法读取null的属性'length'

任何人都可以告诉我如何解决这个问题?

注意:实际上是页面中的两个下拉列表。更改dropdownlist1将调用该函数来更改dropdownlist2。

2 个答案:

答案 0 :(得分:1)

您使用的<%= SecondaryArea.ClientID %>被称为Code Block。 您还可以参考stackoverflow上的this question以获取更多详细信息。

代码块不能放在外部JavaScript文件中,因为它们需要呈现为C#代码。

由于您的JavaScript函数setSecondaryItem在许多页面中使用,当然重复它并不好,您需要在外部JavaScript文件中定义您的函数并在您的文件中调用它(在您需要的任何页面中)代码块作为参数。

您的外部JavaScript文件:

function setSecondaryItem(secondaryAreaId) {
    var select = document.getElementById(secondaryAreaId);
    var len = select.length;
    ...
}

.aspx文件中:

<script type="text/javascript" src="../NormalUseFuction.js"></script>

<script type="text/javascript">
    setSecondaryItem("<%= SecondaryArea.ClientID %>");
</script>

答案 1 :(得分:0)

select.length你应该得到项目长度,如果仍然没有尝试下面的代码行,可能会对你有帮助。

select.options.length