gpt4 book ai didi

Javascript 找不到元素 ID

转载 作者:行者123 更新时间:2023-11-29 23:37:31 24 4
gpt4 key购买 nike

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

但我发现这会报错:Uncaught TypeError: Cannot read property 'length' of null

谁能告诉我如何解决这个问题?

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

最佳答案

<%= SecondaryArea.ClientID %>您正在使用的是 Code Block .也可以引用this question有关更多详细信息,请访问 stackoverflow。

代码块不能放在外部 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>

关于Javascript 找不到元素 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46012914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com