[英]JavaScript error undefined object although object exist
I have the following code 我有以下代码
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div class="full-details-box" name="full_details_box" id="full-details-box"></div>
<hr />
<script type='text/javascript'>
function show_3136(){
document.full_details_box.style.display='block';
}
show_3136();
</script>
</body>
</html>
I get the error: window.document.full_details_box is undefined 我收到错误:window.document.full_details_box未定义
I get the error for the line: 我得到该行的错误:
document.full_details_box.style.display='block';
But I do have a <div>
element with the name full_details_box
, so why the error? 但是我确实有一个名为
full_details_box
的<div>
元素,那么为什么会出错呢?
Don't use the name
attribute for divs. 请勿对div使用
name
属性。 It doesn't even exist. 它甚至不存在。 Use the id, and:
使用ID,并:
document.getElementById('full-details-box')...
function show_3136(){
document.getElementById('full_details_box').style.display='block';
}
To access this element, use getElementById
要访问此元素,请使用
getElementById
function show_3136() {
document.getElementById("full-details-box").style.display = "block";
}
你可以做一个
document.getElementById("full-details-box").style.display='block';
Just to add to your confusion - you may have been thinking about form fields All of these will work on a form field (the first only if you wrap the field in form tags) 只是增加了您的困惑-您可能一直在考虑表单字段,所有这些都将在表单字段上起作用(仅当您将表单字段包装在表单标签中时,这才是第一个)
<html>
<head>
<script type='text/javascript'>
function showFormField(){
document.forms[0].full_details_boxName.style.display='block';
// or document.forms[0].elements["full_details_boxName"].style.display='block';
}
function showNamedField(){
document.getElementsByName("full_details_boxName")[0].style.display='block';
}
function showFieldById(){
document.getElementsById("full_details_boxID").style.display='block';
}
function showFieldByClassName(){ // does not work in all IE browsers
document.getElementsByClassName("full_details_boxCLASS")[0].style.display='block';
}
</script>
</head>
<body>
<form>
<input class="full-details-boxCLASS" name="full_details_boxName" id="full-details-boxID"/>
</form>
</body>
</html>
for a DIV you will use ID or CLASS, but not name 对于DIV,您将使用ID或CLASS,但不使用名称
HTML: HTML:
<div id="full-details-box">
Just some test content
</div>
<hr />
CSS: CSS:
div#full-details-box {
display:none;
}
JS: JS:
function show_3136(){
document.getElementById("full-details-box").style.display = "block";
}
show_3136();
For a working example, see jsFiddle 有关工作示例, 请参见jsFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.