我正在尝试使用 javascript 构建一个界面。界面是一个按钮网格。每一行都是不同的乐器,每一列都有可以触发的节奏模式。
当用户单击一个按钮时,我希望它更改其类,以便背景颜色发生变化,告诉用户它已被激活。
问题是,我的脚本总是针对一行的最后一个按钮。当我尝试强制它定位特定按钮(不是最后一个按钮)时,它会显示“未定义”中的按钮。
pattern1 = ["Clave 1",[1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0],"description"];
pattern2 = ["Clave 2",[1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,0,1],"description"];
pattern3 = ["Clave 3",[1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1],"description"];
pattern4 = ["Clave 4",[1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0],"description"];
pattern5 = ["Clave 5",[1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1],"description"];
pattern6 = ["Clave 6",[1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0],"description"];
pattern7 = ["Clave 7",[1,0,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1],"description"];
pattern8 = ["Clave 8",[1,0,1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0],"description"];
var pattern_collection = [pattern1, pattern2, pattern3, pattern4, pattern5, pattern7, pattern8];
function generate_buttons(instrument_id) {
for (var key in pattern_collection)
{
//creating an array of button for each instrument
var button = new Array();
//creating the button label
var button_text;
button_text = document.createTextNode(pattern_collection[key][0]);
//creating the button in the DOM
button[key] = document.createElement('div');
//by default, the first pattern is shown as playing
if (pattern_collection[key]==pattern1)
button[key].className = "isplaying_pattern_button";
else
button[key].className = "notplaying_pattern_button";
button[key].onclick = function() {
//picking the currently playing button to change its class to not playing
var playing_button = document.querySelector("#"+instrument_id+" .isplaying_pattern_button");
playing_button.className = "notplaying_pattern_button";
//this is where the problem occurs: the script is always targeting the last button of the row
button[key].className = "isplaying_pattern_button";
};
button[key].appendChild(button_text);
var instrument_patterns = document.getElementById(instrument_id);
instrument_patterns.appendChild(button[key]);
}
}