首页 > 关于js中var的变量与ID重名

关于js中var的变量与ID重名

中发现一元素ID为“placeholder”,JS中一函数为:

var placeholder=document.getElementById("placeholder"); //placeholder为一<img>的ID
placeholder.setAttribute("src",source);

后来发现在firefo和ie中出了问题 placeholder.setAttribute("src",source);
这句话运行出了问题
然后 我把那个元素ID改为了"m",其他代码不变 ,结果就正确了!我猜测js中能直接根据ID获取DOM元素,比如 ID.属性(不知对不对),但是为啥ID与变量名重复就会出错呢。。。没懂

源程序如下

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312"/>
<title>图片切换</title>
<style>
body
{
font-family:"Helvetica","Arial",serif;
color:#333;
background-color:#ccc;
margin:1em 10%;
}
h1
{
color:#c60;
background-color:transparent;
}
a
{
color:#c60;
background-color:transparent;
font-weight:bold;
text-decoration: none;
}
ul
{
padding:0;
}
li
{
float:left;
padding:1em;
list-style:none;
}
img
{
display:block;
clear:both;
}
</style>
<script>
Window.onload=showpic;
function showPic(whichpic)
{
    var source=whichpic.getAttribute("href");
    var placeholder=document.getElementById("placeholder");
    placeholder.setAttribute("src",source);alert("!!!");
    var text=whichpic.getAttribute("title");
    var description=document.getElementById("description"); 
    description.childNodes[0].nodeValue=text;
}
</script>
</head>
<body>
<h1>Image Gallery</h1>
<ul>
    <li><a href="D:/网页制作/Fireworks.jpg" onclick="showPic(this); return false;" title="A fireworks display">Fireworks</a></li>
    <li><a href="D:/网页制作/Coffee.jpg" onclick="showPic(this); return false;" title="A cup of black coffee">Coffee</a></li>
    <li><a href="D:/网页制作/Rose.jpg" onclick="showPic(this); return false;" title="A red, red rose">Rose</a></li>
    <li><a href="D:/网页制作/Big_Ben.jpg" onclick="showPic(this); return false;" title="The famous clock">Big Ben</a></li>
</ul>
<img id="placeholder" src="D:/网页制作/001.jpg" width="500px" heigth="300px" alt="my image gallery"/>
<p id="description">请选择一张图片.</p>
</body>
</html>

仅仅想通过更换img的src属性达到本页更换图片的效果


  1. 元素id直接作为变量名进入windows作用域(即进行了隐式声明),引用对应的dom对象。因此默认情况下可以直接通过该变量名访问dom对象。
  2. 题主的代码单独看没有问题,原则上也不会出错,显式声明的变量可以正常覆盖隐式声明的变量。
  3. 在没有更多语境的情况下无法判断题主遇到的问题是啥,建议提供具体出错的类型以及上下文。

update:
注意变量名拼写和大小写:showpigshowPic

Window.onload=showpig;
function showPic(whichpic)
{
...
}
【热门文章】
【热门文章】