我有一个按钮可以触发网页上的脚本。一个实例起作用。当我尝试添加第二个按钮/脚本时,两个按钮仅触发第二个脚本。我知道(想想),这是因为我为按钮定义的变量并不是它们各自的脚本所独有的,而是我尝试尝试的所有方式都破坏了整个过程。
button {
display: block;
cursor: pointer;
margin-left: 10px;}
button:after {
content: " (off)";
}
button.on:before {
content: "✓ ";
}
button.on:after {
content:" ";
}
.frac span {
-webkit-font-feature-settings: "frac" 1;
font-feature-settings: "frac" 1;
}
.onum span {
-webkit-font-feature-settings: "onum" 1;
font-feature-settings: "onum" 1;
}
HTML:
<button name="frac" id="frac">Fractions</button>
<button name="onum" id="onum">Oldstyle Numbers</button>
当按下按钮时,此文本应更改OT功能。
JS:
<script> var btn = document.getElementById("frac"),
body = document.getElementById("textA"),
activeClass = "frac";
btn.addEventListener("click", function(e){
e.preventDefault();
body.classList.toggle(activeClass);
btn.classList.toggle('on');
}); </script>
<!-- onum -->
<script> var btn = document.getElementById("onum"),
body = document.getElementById("textA"),
activeClass = "onum";
btn.addEventListener("click", function(f){
f.preventDefault();
body.classList.toggle(activeClass);
btn.classList.toggle('on');
}); </script>
脚本/按钮之间的差异是我做过的不同事情中的一些变化,但是我大部分时间都回到了开始,所以比较简单。
答案 0 :(得分:0)
在javascript中,您声明的每个变量在整个页面上都是固有可用的。因此,将它们放在单独的标签中将无效。
从本质上讲,您的第二个变量 btn 实际上是覆盖第一个变量。重命名第二个变量为btn2。
或者作为替代,更改行
btn.classList.toggle('on')
到
this.classList.toggle('on')
点击处理程序中的this 始终指向当前被点击的按钮。
答案 1 :(得分:0)
您可以用更少的代码行做到这一点
// you create the array of buttons
let butons = Array.from(document.querySelectorAll("button")),
// you define the _body
_body = document.getElementById("textA")
// for every button in the buttons array (map is an iterator)
butons.map((btn) =>{
//you define the activeClass to be the name attribute of the button
let activeClass = btn.getAttribute("name");
// everytime you click the button
btn.addEventListener("click", (e) =>{
/*this was in your code. I don't know why you need it
e.preventDefault();*/
//you toggle the activeClass & the on class
_body.classList.toggle(activeClass);
btn.classList.toggle("on");
})
})
button {
display: block;
cursor: pointer;
margin-left: 10px;
}
button:after {
content: " (off)";
}
button.on:before {
content: "✓ ";
}
button.on:after {
content: " ";
}
/* I'm using color to visualize the change */
.frac span {
color: red;
}
.onum span {
color: green;
}
<button name="frac" id="frac">Fractions</button>
<button name="onum" id="onum">Oldstyle Numbers</button>
<p id="textA">The variance between the <span>scripts/buttons</span> are some of the changes from different things I've done, but I've gone mostly back to the beginning so it's simpler.</p>