首页 > 解决方案 > 为什么我在使用 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 未捕获的类型错误:无法在 HTMLButtonElement.onclick (deities.html:35) 的 sState (deities.html:21) 处读取 null 的属性“样式”

deities.html:21 指 elmntC.style.display="none"; deities.html:35 指的是按钮的onClick函数调用。

这里发生了什么?为什么我会收到此错误,我该如何解决?已经尝试将脚本移动到正文的底部,但无济于事。

此外,如果有人有任何想法可以更有效地执行此操作(即通过避免 getElementById 调用),请告诉我。

PS对于那些好奇的人,这样做的目的是为我在DnD中的玩家构建一个神灵搜索工具——我是一个普通的DM,并认为当我的玩家想玩牧师时,它会让他们的生活更轻松。在我得到第一个条目后,将开始实施类来锚定搜索。

标签: javascripthtmlcssruntime-errorgetelementbyid

解决方案


sStatehtml页面调用函数有问题。

您需要替换onClick="sState(aegirSimp,aegirExp)"toonClick="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>


推荐阅读