为什么在使用getElementById时不能更改显示样式?

时间:2020-09-30 01:41:46

标签: javascript html css runtime-error getelementbyid

我无法正常运行javascript函数,以下是相关代码:

<script>
function sState(elmntC,elmntO) {
    elmntC=document.getElementById(elmntC);
    elmntO=document.getElementById(elmntO);
    elmntC.style.display="none";
    elmntO.style.display="block";
}
</script>

以及调用函数的正文中的HTML:

<div id="aegir">
    <table id="aegirSimp">
        <tr>
            <th class="name">Aegir</th>
            <th class="alignment">NE</th>
            <th class="title">God of the Sea and Storms</th>
            <th class="domains">Tempest</th>
            <th class="button"><button type="button" onClick="sState(aegirSimp,aegirExp)">+</button></th>
        </tr>
    </table>
    <p id="aegirExp">Aegir<br>CG god of the Sea and Storms<br>Domains: Tempest<br>Symbol: Rough ocean waves<br><br>Norse god of storms and seas, Aegir dwells in an immense hall at the bottom of the seas according to legend.<br><button type="button" id="aegirBC">x</button></p>
</div>

但是,当我运行代码并触发onClick事件时,在Inspect Element中出现以下错误:

deities.html:21未捕获的TypeError:无法读取的属性“样式” 空值 在sState(deities.html:21) 在HTMLButtonElement.onclick(deities.html:35)

deities.html:21指向elmntC.style.display =“ none”; deities.html:35表示按钮onClick函数调用。

这是怎么回事?为什么会出现此错误,我该如何解决?已经尝试将脚本移到正文底部,但无济于事。

此外,如果有人有任何想法可以更有效地做到这一点(即避免调用getElementById),请告诉我。

P.S。对于那些好奇的人来说,这样做的目的是为DnD中的玩家构建神灵搜索工具-我是一名常规DM,并认为这将使我的玩家在玩牧师时更轻松。在我使第一个条目生效之后,以后将开始实现用于锚定搜索的类。

2 个答案:

答案 0 :(得分:4)

在html页面上调用sState函数时出现问题。

您需要将onClick="sState(aegirSimp,aegirExp)"替换为onClick="sState('aegirSimp','aegirExp')"才能将id值发送到sState函数。

function sState(elmntC,elmntO) {
    elmntC=document.getElementById(elmntC);
    elmntO=document.getElementById(elmntO);
    elmntC.style.display="none";
    elmntO.style.display="block";
}
<div id="aegir">
    <table id="aegirSimp">
        <tr>
            <th class="name">Aegir</th>
            <th class="alignment">NE</th>
            <th class="title">God of the Sea and Storms</th>
            <th class="domains">Tempest</th>
            <th class="button"><button type="button" onClick="sState('aegirSimp','aegirExp')">+</button></th>
        </tr>
    </table>
    <p id="aegirExp">Aegir<br>CG god of the Sea and Storms<br>Domains: Tempest<br>Symbol: Rough ocean waves<br><br>Norse god of storms and seas, Aegir dwells in an immense hall at the bottom of the seas according to legend.<br><button type="button" id="aegirBC">x</button></p>
</div>

答案 1 :(得分:2)

错误是您在调用函数时传递id的方式

Id应按如下所示作为字符串传递

 <th class="button"><button type="button" onClick="sState('aegirSimp','aegirExp')">+</button></th>