zzg*_*loo 2 javascript arrays function
快速的问题.
我有一个包含3个函数的数组.当我调用我想要执行的特定函数时,它不响应数组中的特定索引.它只执行所有功能,直到它到达最后一个功能.
这是代码:
<p id="sometext">Change Color</p>
<script>
function paintRed() {
var text = document.getElementById('sometext');
text.style.color = "red";
}
function paintBlue() {
var text = document.getElementById('sometext');
text.style.color = "blue";
}
function paintYellow() {
var text = document.getElementById('sometext');
text.style.color = "yellow";
}
var arrcolor = [ paintRed(), paintBlue(), paintYellow()];
arrcolor[0]; //This returns the yellow color and not red//
</script>
Run Code Online (Sandbox Code Playgroud)
所以我的
换颜色
总是返回黄色(数组中的最后一个函数),无论我调用哪个索引,即(arrcolor [0],arrcolor [1]).希望它有意义.谢谢.
您只能将函数名称(实际上是引用)放在数组中并像这样执行它
var arrcolor = [ paintRed, paintBlue, paintYellow];
arrcolor[2]();
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建一个对象并将每个函数放在其中
var changeColor = {
paintRed :function(text){
text.style.color = "red";
},
paintBlue :function(text){
text.style.color = "blue";
},
paintYellow:function(text){
text.style.color = "yellow";
}
}
var text = document.getElementById('sometext');
changeColor.paintRed(text)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |