[英]document.getElementById is null
I have the following JavaScript working in IE, but not on Chrome and Firefox. 我在IE中使用了以下JavaScript,但在Chrome和Firefox上却没有。 Here is the code:
这是代码:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#applicationSelect').change(function() {
document.getElementById('dropdown').value = "APPLICATION";
});
});
</script>
<input type="hidden" name="dropdown" value="" />
When I look in Firebug, the code errs: 当我查看Firebug时,代码出错:
document.getElementById("dropdown") is null
document.getElementById('dropdown').value = "APPLICATION";
I need your advice. 我需要你的建议。 Thank you in advance.
先感谢您。
If you're using jQuery already, why not use it to set your input value: 如果您已经在使用jQuery,为什么不使用它来设置输入值:
$('#dropdown').val('APPLICATION');
And as others noted, your input's id
was not 'dropdown'. 正如其他人指出的那样,您输入的
id
不是“下拉列表”。
Also, note that to one may use $
in place of jQuery
in most use-cases. 另外,请注意,在大多数用例中,可能会使用
$
代替jQuery
。
The problem is that your input
element doesn't have an id
! 问题是您的
input
元素没有id
! Change name
to id
, or add an id
too: 将
name
更改为id
,或者也添加一个id
:
<input type="hidden" name="dropdown" id="dropdown" value="" />
Alternatively, if you don't want to add an id
, you could use getElementsByName
(which doesn't work very well cross-browser), or you could use a jQuery attribute selector: 另外,如果您不想添加
id
,则可以使用getElementsByName
(跨浏览器效果不佳 ),或者可以使用jQuery属性选择器:
$("input[name='dropdown']").val("APPLICATION");
Update 更新资料
I just noticed that you said in your question that it was working in IE. 我只是注意到您在问题中说它正在IE中运行。 That means you must be using a pretty old version of IE, because
getElementById
in IE7 and below incorrectly selects elements by name
, as well as id
. 这意味着您必须使用旧版本的IE,因为IE7及更低版本中的
getElementById
错误地通过name
和id
选择元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.