js问题,为什么获取不了id元素??求解
PicList.prototype.run = function(){ log(this.elem) //null } 这句获取了空值...哪里出错了?
JScript code
function log(i){ return console.log(i); }
function $ (id)
{
if(typeof id === "string"){
return document.getElementById(id);
}else{
return id;
}
}
function PicList(){
this.elem = $(arguments[0]);
this.arr = [];
var iTarget = [
{ left:0 },
{ left:50 },
{ left:100 },
{ left:150 },
{ left:200 }
];
this.run();
}
PicList.prototype.run = function(){
log(this.elem) //null
}
Animate.prototype = new PicList("wrap");
function Animate(){
log(this.arr)
}
var obj = new Animate();
//HTML
<div id="wrap"> </div>
------解决方案--------------------
<script type="text/javascript">
function log(i){ return console.log(i); }
function $ (id)
{
if(typeof id === "string"){
return document.getElementById(id);
}else{
return id;
}
}
function PicList(){
this.elem = $(arguments[0]);
alert(this.elem.id);
this.arr = [];
var iTarget = [
{ left:0 },
{ left:50 },
{ left:100 },
{ left:150 },
{ left:200 }
];
this.run();
}
PicList.prototype.run = function(){
log(this.elem) //null
}
</script>
</head>
<body>
<div id="wrap"> </div>
<script type="text/javascript">
Animate.prototype = new PicList("wrap");
function Animate(){
log(this.arr)
}
var obj = new Animate();
</script>
这样试试 貌似是因为Animate.prototype = new PicList("wrap");时你的那个div还没加载进来,所以为null
我也是猜的 js继承那块没好好看