我是 javascript 新手,我今天刚刚开始学习它。我正在尝试制作一个功能,该功能将在单击按钮时更改多个按钮类。
例如,如果单击按钮 2,则类将更改为 ,btn-blue
其余按钮将更改为btn-red
。
但我收到两个错误:
Uncaught ReferenceError: menu is not defined"
和
"Uncaught ReferenceError: e is not defined"
const changeClass = (e, r, a) => e.classList.remove(r); e.classList.add(a);
const menu = (btn) => {
const b1 = document.getElementById(btn);
const b2 = document.querySelectorAll('#btn1, #btn2, #btn3');
Array.from(b2).forEach(b => {
if (b.classList.contains('btn-blue')) {
changeClass(b, 'btn-blue', 'btn-red');
}
});
changeClass(b1, 'btn-red', 'btn-blue');
}
.btn {
display: inline-block;
height: 40px;
line-height: 40px;
padding: 0 20px;
background: #444;
color: #eee;
border: 0;
font-size: 14px;
vertical-align: top;
text-align: center;
text-decoration: none;
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
border-radius: 4px;
transition: all 0.15s ease-in-out;
}
.btn:hover,
.btn:active {
background-color: #555;
color: #fff;
}
.btn-red {
background-color: #b3353c;
}
.btn-red:hover,
.btn-red:active {
background-color: #cb575b;
}
.btn-blue {
background-color: #1d8dee;
}
<button class="btn btn-blue" id="btn1" onclick="menu('btn1');">button one</button> <br />
<button class="btn btn-red" id="btn2" onclick="menu('btn2');">button two</button> <br />
<button class="btn btn-red" id="btn3" onclick="menu('btn3');">button three</button> <br />
你可以试试这个。您缺少用于定义函数开始和结束的大括号。
const changeClass = (e, r, a) => { e.classList.remove(r); e.classList.add(a); }
const menu = (btn) => {
const b1 = document.getElementById(btn);
const b2 = document.querySelectorAll('#btn1, #btn2, #btn3');
Array.from(b2).forEach(b => {
if (b.classList.contains('btn-blue')) {
changeClass(b, 'btn-blue', 'btn-red');
}
});
changeClass(b1, 'btn-red', 'btn-blue');
}
.btn {
display: inline-block;
height: 40px;
line-height: 40px;
padding: 0 20px;
background: #444;
color: #eee;
border: 0;
font-size: 14px;
vertical-align: top;
text-align: center;
text-decoration: none;
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
border-radius: 4px;
transition: all 0.15s ease-in-out;
}
.btn:hover,
.btn:active {
background-color: #555;
color: #fff;
}
.btn-red {
background-color: #b3353c;
}
.btn-red:hover,
.btn-red:active {
background-color: #cb575b;
}
.btn-blue {
background-color: #1d8dee;
}
<button class="btn btn-blue" id="btn1" onclick="menu('btn1');">button one</button> <br />
<button class="btn btn-red" id="btn2" onclick="menu('btn2');">button two</button> <br />
<button class="btn btn-red" id="btn3" onclick="menu('btn3');">button three</button> <br />
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句