我试图将数组中的变量作为聚合物元素的成员进行访问。但是我一直在"无法读取未定义的属性NaN"。这是我的代码,我在this.images [this.x]得到了错误:
<link rel="import" href="bower_components/polymer/polymer.html">
<polymer-element name="big-picture" noscript>
<template>
<style>
#crop
{
display: block;
position: relative;
}
#mainpictop
{
position: absolute;
width: 100%;
}
#mainpicbottom
{
position: absolute;
width: 100%;
}
</style>
<div id="crop">
<img id="mainpictop" src={{pic1source}} style="opacity:{{pic1opacity}}"></img>
<img id="mainpicbottom" src={{pic2source}} style="opacity:{{pic2opacity}}"></img>
</div>
</template>
<script>
Polymer('big-picture',{
x:1,
currentTop:0,
currentBottom:1,
numpics:5,
transitionspeed:200,
images: new Array,
pic1opacity: 1,
pic2opacity:1,
pic1source: "img/main/1.jpg",
pic2source: "img/main/2.jpg",
ready: function(){
for (i=0;i<this.numpics;i++)
{
this.images[i]="img/main/".concat(i+1).concat(".jpg");
}
setInterval(function() {
changeImageSrc()
},this.transitionspeed);
}
});
function changeImageSrc() {
if(this.pic1opacity==1)
{
this.pic1opacity=0;
this.pic2opacity=1;
if (this.currentTop!=this.currentBottom)
this.pic2source = this.images[this.x];
else
{
this.x=this.x+1;
if(this.x===this.numpics)
this.x=0;
this.pic2source = this.images[this.x];
}
this.currentBottom=this.x;
}
else
{
this.pic2opacity=0;
this.pic1opacity=1;
if (this.currentTop!=this.currentBottom)
this.pic1source = this.images[this.x];
else
{
this.x=this.x+1;
if(this.x===this.numpics)
this.x=0;
this.pic1source = this.images[this.x];
}
this.currentTop=this.x;
}
this.x=this.x+1;
if(this.x===this.numpics)
this.x=0;
}
</script>
</polymer-element>
我才开始学习聚合物,所以请不要太苛刻。
答案 0 :(得分:1)
这是一个范围问题。使用&#34;这个&#34;时要非常小心在其他功能中,因为&#34;这个&#34;改变它所处的功能。在你的情况下,&#34;这个&#34;变量已设置为changeImageSrc()的上下文。
一个简单的解决方法是存储对&#34;这个&#34;在另一个变量(var _this = this;
)中,当需要对Polymer变量执行操作时使用该新变量。