我正在尝试使用 javascript 和 css 制作一个按钮,当单击该按钮时,它将更改被单击元素的类,以使用户清楚它是当前选定的按钮。
页面上有四个按钮。我还没有实施第四个。蛮力代码(显示后)正在工作。
function selected_button(opCode){
switch(opCode){
case 1:
document.getElementById('button1').className += "selected";
document.getElementById('button2').className = document.getElementById("button2").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
document.getElementById('button3').className = document.getElementById("button3").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
document.getElementById('button4').className = document.getElementById("button4").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
break;
case 2: //Really similar to case 1 but shifted numbers around
document.getElementById('button2').className += "selected";
document.getElementById('button1').className = document.getElementById("button1").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
document.getElementById('button3').className = document.getElementById("button3").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
document.getElementById('button4').className = document.getElementById("button4").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
break;
default: //really similar to case 1 but shifted numbers around
document.getElementById('button3').className += "selected";
document.getElementById('button1').className = document.getElementById("button1").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
document.getElementById('button2').className = document.getElementById("button2").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
document.getElementById('button4').className = document.getElementById("button3").className.replace( /(?:^|\s)selected(?!\S)/ , '' );
}
}
我想对此做一个更通用的功能,所以我想出了以下内容:
function general_selected(selected_elem_num, num_elem, elem_name, desired_class){
var i = 0;
for( i = 0; i < num_elem + 1; i++){ //dehighlights all options
document.getElementById(elem_name + i.toString()).className =
document.getElementById(elem_name + i.toString()).className.replace
( /(?:^|\s) *should be a parameter here* (?!\S)/ , '' );
/* code wrapped for readability - above is all one statement */
}
//highlights selected option
document.getElementById(elem_name + selected_elem_num).className
+= desired_class;
}
以下两个函数调用实际上应该是等效的:
selected_button(1);
general_selected( 1, 4, 'button', 'selected');
我遇到的2个问题:
1)我不知道如何将所需的类作为参数插入到正则表达式中。
2) for 循环中非常长的方法导致错误。该错误似乎是持久的,因为即使我将 for 循环中的方法替换为以下内容,我也会收到相同的错误:
document.getElementByID(elem_name + i.toString()).className = desired_class;
基于此线程的代码松散: Change an element's class with JavaScript