gpt4 book ai didi

javascript - 我想将 onclick 函数分配给这样的按钮,但它不起作用,为什么?

转载 作者:行者123 更新时间:2023-11-28 12:51:45 24 4
gpt4 key购买 nike

我想将 onclick 函数分配给这样的按钮

window.onload = function() {
var tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
console.log(tablinks[i].innerText);
tablinks[i].onclick = openCity(event,tablinks[i].innerText);
}
}



function openCity(evt,cityName) {
var i, tabcontent, tablinks;
console.log(cityName);
// Get all elements with class="tabcontent" and hide them
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"
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";
evt.currentTarget.className += " active"};

我看到当窗口加载时它会将日志发送到控制台:

London panel.js:4:11 London panel.js:14:9 Paris panel.js:4:11 Paris panel.js:14:9 Tokyo panel.js:4:11 Tokyo panel.js:14:9

但是当我单击按钮时 onclick 不会触发。为什么?

最佳答案

两个问题,首先用let声明变量(i)为变量创建 block 作用域并在匿名函数内调用该函数。

演示:

window.onload = function() {
var tablinks = document.getElementsByClassName("tablinks");
for (let i = 0; i < tablinks.length; i++) {
tablinks[i].onclick = function(){openCity(event,tablinks[i].innerText)};
}
}
function openCity(e, text){
console.log(text);
}
<ul>
<li class="tablinks">tab1</li>
<li class="tablinks">tab2</li>
<li class="tablinks">tab3</li>
</ul>

关于javascript - 我想将 onclick 函数分配给这样的按钮,但它不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60903554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com