getElementbyId 的问题
我在 getElementbyId 方面遇到问题,如下所示:
<script type="text/javascript">
<!--
function show_links(locale) {
var box = document.getElementById(locale);
if(box.style.display == "none") {
box.style.display = "inline";
}
else {
box.style.display = "none";
}
}
//-->
</script>
<div class="link"><strong><a href="javascript:show_links(test);">Test</a></strong></div>
<div class="test"> Blah blah blah. This content comes and goes. </div>
所以您有代码。当我单击链接“测试”时,它应该隐藏“等等等等文本”。再次单击时,它应该显示。但是,我有一个奇怪的问题。我通过调试器处理了代码,似乎行 var box = document.getElementById(locale);
无法正常工作。 box
被设置为 null。任何人都可以推理为什么吗?
I'm having a problem with getElementbyId as follows:
<script type="text/javascript">
<!--
function show_links(locale) {
var box = document.getElementById(locale);
if(box.style.display == "none") {
box.style.display = "inline";
}
else {
box.style.display = "none";
}
}
//-->
</script>
<div class="link"><strong><a href="javascript:show_links(test);">Test</a></strong></div>
<div class="test"> Blah blah blah. This content comes and goes. </div>
So there you have the code. When I click the link "Test", it should hide the "blah blah blah text". When clicked again, it should show. However, I have an odd problem. I processed the code through a debugger, and it seems that the line var box = document.getElementById(locale);
is not working correctly. box
is being set to null. Can anyone theorize why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有几个问题。首先是关键的:
show_links
函数的值是变量test
。这等于undefined
因此它不会匹配任何内容。您需要为尝试匹配的元素提供 id 并传递字符串而不是未定义的值。
然后是较小的问题。
className
属性,并在样式表中定义样式。inline
和none
之间摆弄 div,但 div 的默认显示值为block
。有理由将 div 样式设置为内联,但大多数时候您应该使用另一个元素。You have several problems. First the critical ones:
show_links
function is the variabletest
. This is equal toundefined
so it isn't going to match anything.You need to give the element you are trying to match an id and pass a string instead of an undefined value.
Then the lesser issues.
className
property, and have your styles defined in a stylesheet.inline
andnone
, but the default display value for a div isblock
. There are reasons to have a div styled inline, but most of the time you should be using another element.test
是一个未知标识符。你在哪里定义的?你的意思是喂一根绳子吗?此行中没有 id 为
test
的元素。使用正确的属性id
。test
is an unknown identifer. Where did you define it? Did you mean to feed a string?There is no element with an id of
test
in this line. Use the proper attributeid
.