JavaScript找不到元素ID [英] Javascript cannot find element id

查看:68
本文介绍了JavaScript找不到元素ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个javascript文件中有我的javascript函数,因为该函数使用了我的大部分页面.

I have my javascript function in a javascript file because this function use most of my page.

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

我也将此放在了我的页面

I also put this in my page

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

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

I call this function when a dropdownlist change

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

但是我发现这会出错:Uncaught TypeError:无法读取null的属性"length"

But I found that this will get an error : Uncaught TypeError: Cannot read property 'length' of null

任何人都可以向我展示如何解决此问题?

Anyone can show me how to solve this problem?

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

Note: actually is two dropdownlist in page. change dropdownlist1 will call the function to change dropdownlist2.

推荐答案

您正在使用的<%= SecondaryArea.ClientID%> 称为此问题以了解更多信息.

This <%= SecondaryArea.ClientID %> that you are using is known as Code Block. You can also refer to this question on stackoverflow for more details.

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

Code Blocks can't be placed in external JavaScript files because they need to be rendered as C# code.

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

As your JavaScript function setSecondaryItem is used in many pages and of course it's not good to repeat it, you need to define your function in an external JavaScript file and call it (in any page you need) with your Code Block as an argument.

您的外部JavaScript文件:

Your external JavaScript file:

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>

这篇关于JavaScript找不到元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆