我正在尝试使用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');
我遇到了两个问题:
1)我不知道如何将所需的类作为参数插入正则表达式。
2)for循环中真正长的方法导致错误。该错误似乎是持久的,因为即使我用以下内容替换for循环中的方法,我也会得到相同的错误:
document.getElementByID(elem_name + i.toString()).className = desired_class;
代码松散地基于这个线程: Change an element's class with JavaScript
答案 0 :(得分:0)
将事件侦听器添加到根节点并跟踪实际目标。
document.addEventListener('click', function(event){
var old = document.querySelector(".selected");
old.className = old.className.replace( /(?:^|\s)selected(?!\S)/ , '' );
event.target.className += " selected";
}, false);
答案 1 :(得分:0)
new Regex(string)
reg = new Regex('?:^|\s)'+desired_class+'(?!\S)');
for(i = 1; i < num_elements + 1 .....
正如他们所说,剩下的就是留给读者的练习