gpt4 book ai didi

javascript - 为什么我的JavaScript抛出 “cannot read property style of null”?

转载 作者:行者123 更新时间:2023-12-03 07:51:48 25 4
gpt4 key购买 nike

以下是相关的javascript代码。我正在将正确的值传递给该方法,该方法用于document.getElementById(tabName).style.display ='block'行(错误所在)。我创建了新的ID元素,并将其传递给了我。我不明白
出现错误的行:document.getElementById(tabName).style.display ='block';
它在最后。
谢谢您的帮助,我有点新手,可能无法完全理解其中的复杂部分。我真的可以使用帮助。

function addTab() {

//create a new div element
const newDiv = document.createElement('div');

//create the id and add tab content class
newDiv.id = "newtab"; //sets id name for div
newDiv.classList.add("tablinks"); //sets class for div

//give tab some text
const tabContent = document.createTextNode("Testing the add tab button!");
newDiv.appendChild(tabContent);

//create the tab
var btn = document.createElement("button"); //creates button
btn.className = "tablinks"; //sets class for button

//give onclick event to button
var event = Event;
btn.onclick = openTab(event, 'newtab');
document.getElementByClassName("tab").appendChild(btn);

//add the newly created element and its content into the DOM
const currentDiv = document.getElementById("addnewtab");
document.body.insertBefore(newDiv, currentDiv);
}

/* RECENT 10-K NOTIFICATION FEED START */
function openTab(evt, tabName) {

var i, tablinks;
let tabcontent = document.getElementsByClassName("tabcontent");

for (let tab of tabcontent) {
tab.style.display = "none";
}

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

document.getElementById(tabName).style.display = 'block';
evt.currentTarget.className += " active";

}

最佳答案

您看到的错误“无法读取null的属性样式”意味着它正在尝试访问style返回的元素的document.getElementById(tabName)属性。
如果找不到此元素(返回null),那么您将确切地看到错误消息。
为了避免该错误,我建议在访问style属性之前添加一个类型防护:

let tabEl = document.getElementById(tabName);
if (tabEl) {
tablEl.style.display = 'block';
}

关于javascript - 为什么我的JavaScript抛出 “cannot read property style of null”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64127296/

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