为什么我的javascript没有通过它的id获取元素? [英] Why is my javascript not getting the element by its id?

查看:89
本文介绍了为什么我的javascript没有通过它的id获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个aspx页面,我试图在下拉列表中选择的国家是美国时隐藏表格行。我一直收到一个null引用错误(或者与javascript等价的),因为它找不到其中的一个元素。



这里是javascript

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


};
< / script>

出于某种原因,它无法找到元素country。



以下是country的样子:

 < tr> 
< th class =style1>< strong>国家/地区:< / strong>< / th>
< th class =style2>
< asp:DropDownList onchange =cntryslct()id =country...> stuff< / asp:DropDownList>
< / th>
< / tr>

不知道它是否重要,但国家在staterow之后,元素被隐藏,显示。



为什么它的id无法找到元素?是因为元素也是调用脚本的元素吗?

解决方案

所有ASPX组件的ID都发生了变化

你有两个选择:
$ b $ 1)设置属性ClientID =Static你的ASPX组件;



2)或者获取 Control.ClientID ,例如:

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


I have an aspx page and I am trying to hide a table row when the country selected in a drop down list is "US". I keep getting a null reference error (or the javascript equivalent) because it can't find one of the elements.

Here is the 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>

For some reason it can't find the element "country".

Here is what "country" looks like:

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

Not sure if it matters, but "country" is after "staterow", the element being hidden and shown.

Why can it not find the element by its id? Is it because the element is also the element where the script is being called?

解决方案

The ID of all of your ASPX components changes after page renderization.

You have two alternatives:

1) Set the property ClientID="Static" of your ASPX components;

2) Or get the Control.ClientID at runtime, for example:

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

这篇关于为什么我的javascript没有通过它的id获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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