我正在尝试创建一些 JavaScript 代码,根据元素的类名监听元素上的单击事件。这会触发一个函数,该函数会更改同一元素的类,从而允许元素单击事件触发不同的函数,以实现按钮的切换效果。
但是,虽然初始单击事件成功并触发了该函数,但更改元素的类名不会导致 JavaScript 触发新函数,而是会继续使用原始函数。
function tioDisable(e) {
var tioButton = document.getElementById(e.explicitOriginalTarget.name + '-tioButton');
tioButton.classList.remove('tio-enable');
tioButton.classList.add('tio-disable');
}
var tioDis = document.getElementsByClassName('tio-disable');
for (var i = 0; i < tioDis.length; i++) {
tioDis[i].addEventListener('click',tioDisable);
}
function tioEnable(e) {
var tioButton = document.getElementById(e.explicitOriginalTarget.name + '-tioButton');
tioButton.classList.add('tio-enable');
tioButton.classList.remove('tio-disable');
}
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
<img class="tio-enable" src="image.png" name="test" id="test-tioButton">`
我最初尝试使用 querySelectorAll,但我在研究中读到这实际上创建了一个静态元素列表,我的研究表明使用 getElementsByClassName 应该创建一个动态列表,但这对我不起作用。有更好的方法吗?
最佳答案
代码第一次运行时,会根据以下代码添加click
事件。因为初始代码有类tio-enable
。
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
现在,如果您单击图像,它将调用以下函数。
function tioEnable(e) {
var tioButton = document.getElementById(e.explicitOriginalTarget.name + '-tioButton');
tioButton.classList.add('tio-enable');
tioButton.classList.remove('tio-disable');
}
在上面的代码中,您添加了类名 tio-enable
,该类已经具有并删除了 tio-disable
。所以你的原始内容没有任何改变。所以这将一次又一次地执行相同的场景。
因此,您必须将 click
事件监听器更改为 tioDisable
或在 tioEnable
函数中添加类 tio-Disable
并删除类 tio-Enable
。
现在可以用了吗? 否。因为更改类名后,您没有绑定(bind)任何事件。它仍然与旧的点击监听器绑定(bind)。因此,您必须为 tioDisable
类绑定(bind) click
监听器,并对其他函数也执行相同的操作。检查下面的代码片段。
function tioDisable(e) {
var tioButton = document.getElementById(e.target.name + '-tioButton');
console.log("called to Disable");
tioButton.classList.remove('tio-enable');
tioButton.classList.add('tio-disable');
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
}
function tioEnable(e) {
var tioButton = document.getElementById(e.target.name + '-tioButton');
console.log("called to Enable");
tioButton.classList.add('tio-disable');
tioButton.classList.remove('tio-enable');
var tioDis = document.getElementsByClassName('tio-disable');
for (var i = 0; i < tioDis.length; i++) {
tioDis[i].addEventListener('click',tioDisable);
}
}
var tioEn = document.getElementsByClassName('tio-enable');
for (var i = 0; i < tioEn.length; i++) {
tioEn[i].addEventListener('click',tioEnable);
}
.tio-enable {
border:2px solid green;
padding:10px;
}
.tio-disable {
border:2px solid red;
padding:10px;
}
<img class="tio-enable" src="image.png" name="test" id="test-tioButton">
也许会有一个简单的解决方案。但根据你的代码,我已经给出了我的解决方案。
关于javascript - 如何动态切换类以点击触发不同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49422204/