【问题标题】:Why is my javascript not getting the element by its id?为什么我的 javascript 没有通过它的 id 获取元素?
【发布时间】:2014-07-09 04:55:48
【问题描述】:

我有一个 aspx 页面,当下拉列表中选择的国家/地区为“美国”时,我试图隐藏表格行。我不断收到空引用错误(或等效的 javascript),因为它找不到其中一个元素。

这里是javascript

<script type="text/javascript">
    function cntryslct() {
        var elem = document.getElementById("staterow");
        var dropdown = document.getElementById("country");
        elem.style.display = (dropdown.value; != "US") ? "none" : "";


    };
</script>

由于某种原因,它找不到元素“国家”。

下面是“国家”的样子:

<tr>
    <th class="style1"><strong>Country: </strong></th>
    <th class="style2">
        <asp:DropDownList onchange="cntryslct()" id = "country" ...>stuff</asp:DropDownList>
    </th>
</tr>

不确定是否重要,但“国家”在“staterow”之后,该元素被隐藏和显示。

为什么不能通过 id 找到元素?是不是因为元素也是脚本被调用的元素?

【问题讨论】:

  • 这是因为页面渲染后ID发生了变化。您应该在下拉列表中使用 ClientID="Static"
  • 在处理 js 时,始终查看呈现的 html(浏览器、查看源代码)而不是原始 aspx。我想您的id 与您在处理后的想法完全不同。
  • 根据您使用的浏览器,您可以右键单击有问题的选择元素,然后单击“检查元素”。在这里你可以检查它是否真的有一个“国家”的ID。
  • 你有一个额外的“;”在这种情况下,你是说elem.style.display = (dropdown.value != "US" ? "none" : ""); 吗?
  • 是的,我注意到在 Yuriy 之后,但感谢 cr0ss 解决了它。总的来说,我对 javascript、html 和网页设计不太熟悉。你应该做出回答,这样我才能接受。

标签: javascript html asp.net webforms


【解决方案1】:

所有 ASPX 组件的 ID 在页面呈现后都会发生变化。

你有两种选择:

1) 设置 ASPX 组件的属性 ClientID="Static";

2) 或者在运行时获取Control.ClientID,例如:

var dropdown = document.getElementById('<%= country.ClientID %>');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2013-01-16
    相关资源
    最近更新 更多