在“ currentTarget”处,运行代码时出现错误。
我尝试研究问题,但找不到任何有效的方法
// London is active by defult
document.getElementById("London").style.display = "block";
event.currentTarget.className += " active";
function openCity(cityName) {
// Get all elements with class="tabcontent" and hide them
let tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
let tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace("active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(cityName).style.display = "block";
event.currentTarget.className += "active";
}
index.js:12未捕获的TypeError:无法读取的属性“ currentTarget” 在index.js:12上未定义
答案 0 :(得分:0)
此代码都不在事件侦听器中,因此没有event
变量。我猜想您要将类添加到与您设置样式相同的元素中。
与其在className
字符串上进行操作,不如在classList
上使用函数。
// London is active by defult
var defaultElement = document.getElementById("London");
defaultElement.style.display = "block";
defaultElement.classList.add("active");
function openCity(cityName) {
// Get all elements with class="tabcontent" and hide them
let tabcontent = document.getElementsByClassName("tabcontent");
for (let i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
let tablinks = document.getElementsByClassName("tablinks");
for (let i = 0; i < tablinks.length; i++) {
tablinks[i].classList.remove("active");
}
// Show the current tab, and add an "active" class to the button that opened the tab
var newElement = document.getElementById(cityName);
newElement.style.display = "block";
newElement.classList.add("active");
}
答案 1 :(得分:0)
添加到您在html代码中定义的函数参数事件
例如:onclick="openCity(event)"