gpt4 book ai didi

javascript - 如何直接在JavaScript代码中而不是html标签中实现onclick函数?

转载 作者:行者123 更新时间:2023-12-02 22:04:10 25 4
gpt4 key购买 nike

以下链接包含我存储在 codepen 上的项目:

[https://codepen.io/adan96/pen/ExaRgOe?editors=1010]

以前我的 onclick 函数位于 html 标签中,但我想让它直接在 JS 代码中工作:

document.getElementById("requestTypeSelection").selectedIndex = -1;
document.getElementById("requestSubtypeSelection").selectedIndex = -1;
document.getElementsByClassName("batch")[0].selectedIndex = -1;
document.getElementsByClassName("batch")[1].selectedIndex = -1;

document.getElementById("button1").onclick = function() {openTab("click", generalData)};
document.getElementById("button2").onclick = function() {openTab("click", materialData)};

function openTab(evt, tabName) {
var i, tabcontent, tablinks;

tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}

tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
if (tabName != "generalData") {
tablinks[0].style.backgroundColor = "#cfdeed";
} else {
tablinks[0].style.backgroundColor = "#8eb3dc";
}
}
document.getElementById(tabName).style.display = "block";
event.currentTarget.className += " active";
}

window.onload = function() {
var i, tabcontent, tablinks;

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", "");
}

document.getElementById("generalData").style.display = "block";
event.currentTarget.className += " active";
tablinks[0].style.backgroundColor = "#8eb3dc";
};

var $select1 = $("#select1"),
$select2 = $("#select2"),
$options = $select2.find("option");

$select1
.on("change", function() {
$select2.html($options.filter('[value="' + this.value + '"]'));
})
.trigger("change");

点击按钮1和按钮2后,我应该在它们下面看到它们的选项卡,但什么也没有出现。您能提供如何修改代码的建议吗?

最佳答案

使用EventTarget.addEventListener将事件绑定(bind)到元素。 onclick 不是这样工作的。

document.getElementById("button1").addEventListener("click", function() {
console.log("Clicked");
});
<button id="button1">Click Me</button>

如果openTab("click",materialData)的第一个参数是实际的事件对象,那么你应该这样做:

document.getElementById("button1").addEventListener("click", function(event) {
console.log("Clicked");
openTab(event, materialData)
});

关于javascript - 如何直接在JavaScript代码中而不是html标签中实现onclick函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59771877/

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