[0]是否支持通过变量访问对象
我用代码的方式来创建按钮,每个按钮的var及label都是数组的元素(已成功创建)。
我想通过for循环为变量赋不同的值来创建单击事件,但好像不能实现(如下buttonName是一个变量,this.py_sm是一个数组,具体见附件)
我想通过for循环为变量赋不同的值来创建单击事件,但好像不能实现(如下buttonName是一个变量,this.py_sm是一个数组,具体见附件)
for(var i=0;i<this.py_sm.length;i++){完整代码如下,main_script是挂载到runtime中:
var buttonName = "btn_"+i;
this.buttonName.on(Laya.Event.CLICK,this,function(){
console.log(this.buttonName.label);
});
}
export default class main_script extends Laya.Scene {
constructor() {
super();
this.py_sm = ['b','p','m','f','d','t','n','l','g','k','h','j','q','x','zh','ch','sh','r','z','c','s','y','w'];
this.py_ym = ['a','o','e','i','u','','ai','ei','ui','ao','ou','iu','ie','','er','an','en','in','un','','ang','eng','ing','ong'];
this.py_ztrd = ['zhi','chi','shi','ri','zi','ci','si','yi','wu','yu','ye','yue','yin','yun','yuan','ying'];
this.button_size = 160;
this.column = 8;
this.row = 5;
}
onEnable() {
Laya.stage.bgColor = "#aaaaaa";
// 创建按钮
for (var i=0;i<this.row;i++){
for (var j=0;j<this.column;j++){
if(i*this.column + j>=this.py_sm.length){
break;
}
var obj = new Laya.Button();
obj.var = "btn_" + i;
obj.labelSize = 50;
obj.sizeGrid = "8,8,8,8";
obj.skin = "comp/button.png";
obj.stateNum = 3;
obj.label = this.py_sm[i*this.column + j];
obj.x = j * this.button_size;
obj.y = i * this.button_size;
obj.width = this.button_size;
obj.height = this.button_size;
Laya.stage.addChild(obj);
}
}
// 通过给变量赋值,以值的方式来循环为按钮添加单击事件
for(var i=0;i<this.py_sm.length;i++){
var [i][b]buttonName[/b][/i] = "btn_"+i;
this.[b][i]buttonName[/i][/b].on(Laya.Event.CLICK,this,function(){
console.log(this.buttonName.label);
});
}
}
}
没有找到相关结果
已邀请:
要回复问题请先登录
1 个回复
伍德春
赞同来自:
// 将所有按钮放到数组中
var obj_array = [];
for(var i=0;i<this.py_sm.length;i++){
var buttonObj = Laya.stage.getChildByName("btn_"+i);
obj_array.push(buttonObj);
}
// 为每个数组中的对象添加CLICK事件
obj_array.forEach(element => {
element.on(Laya.Event.CLICK,this,function(){
console.log(element.label);
// 播放对应的声音
Laya.SoundManager.playSound("sound/" + element.label + ".mp3", 1);
});
});