我有一个简单的代码,它使 div 元素在页面上来回移动。一切正常,但是当我尝试使用命名空间时,它不再起作用,并且我收到关于数字 0 的“Uncaught syntaxError : Unexpected identifier”。这是为什么呢?您将如何在这里使用命名空间来使其工作?我刚刚开始命名空间,发现它有点困惑。
<script>
var MyNameSpace = MyNameSpace|| {
var x: 0;
var y: 20;
var direction = "droite";
bouger: function () {
if (direction == "droite") {
x:x+1;
}
else if (direction =="gauche") {
x: x-1;
}
document.getElementById("bouge").style.left: x + "px";
document.getElementById("bouge").style.top: y + "px";
if (x == 200) {
direction = "gauche";
}
else if (x ==0) {
direction = "droite";
}
}
setInterval(bouger, 5);
};
MyNameSpace.bouger();
</script>
最佳答案
您的代码中有几个语法错误。 var x:0
, x: x-1
等等。
除此之外,使用 ||
我们分配的运算符 MyNameSpace
对象字面量(如果尚不存在)。您正在为它分配一个代码块 {}
.相反,您可以更改 x
, y
和 direction
到 MyNameSpace
的属性(property)并使用 this
关键词。而且你不能打电话setInterval(bouger, 5)
在对象字面量中。因此,您可以使用 setTimeout
内bouger
函数在 5 ms 后重复该函数:
var MyNameSpace = MyNameSpace || {
x: 0,
y: 20,
direction: "droite",
bouger: function() {
if (this.direction == "droite") {
this.x++;
} else if (this.direction == "gauche") {
this.x--;
}
document.getElementById("bouge").style.fontSize = this.x + "px";
document.getElementById("bouge").style.top = this.y + "px";
if (this.x == 200) {
this.direction = "gauche";
} else if (this.x == 0) {
this.direction = "droite";
}
setTimeout(this.bouger.bind(this), 5);
}
};
MyNameSpace.bouger();
<div id="bouge">text</div>
(
style.left
不起作用。所以我正在使用 fontSize
)
关于javascript - 具有命名空间的意外标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55990984/