javascript - 为什么我在使用 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,并认为当我的玩家想玩牧师时,它会让他们的生活更轻松。在我得到第一个条目后,将开始实施类来锚定搜索。
解决方案
sState
html页面调用函数有问题。
您需要替换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>
推荐阅读
- javascript - 如何使用递归函数从对象获取绝对路径?
- centos7 - systemctl 无法在 centos 7 上启动 freeRadius
- python - 当并行运行的两种方法之一返回结果时,如何终止整个程序?
- awk - 用 AWK 替换所有非字母数字字符
- c# - 在 WPF 应用程序中托管 ASP Web Api 不会正常停止
- ios - iOS 上的 SwiftUI 选项卡视图,如 Safari
- javascript - Leaflet:标记图标和 markerCluster 一起显示在地图上,并带有 fetch
- c# - Swashbuckle 生成多态字段
- vue.js - VueJS 中两个本地日期时间输入的最小值和最大值
- shopify - 遍历 Liquid 中的数组元素