单击第二个单选按钮时要显示的 div 内的信息
我有两个单选按钮和一个 div:
<input type='radio' name='option' value='test1' />
<input type='radio' name='option' value='test2' />
<div style="display:none">
Hidden info
</div>
我想要的是当单击第二个单选按钮时显示 div 内的信息,但是一旦它们切换到另一个单选按钮,我希望它消失。我还想用原始 JavaScript 来完成此操作。
我该怎么做呢?
I have two radio buttons and a div:
<input type='radio' name='option' value='test1' />
<input type='radio' name='option' value='test2' />
<div style="display:none">
Hidden info
</div>
What I would like is for the information inside the div to be displayed when the second radio button is clicked, but as soon as they switch to the other radio button I would like it to go away. I would also like to do this in raw JavaScript.
How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以在两个单选按钮上挂钩
click
事件,然后使用您感兴趣的单选按钮的checked
属性来确定的可见性div
通过其.style.display
属性(“none”表示隐藏,“”表示默认 [block])。您可以通过多种方式访问单选按钮和
div
的 DOM 元素。最简单的方法之一是,如果您给它们id
值:那么就很简单(live example ):
确保该脚本位于
body
元素的末尾,或将其包装在window.onload
或类似处理程序中。但是,如果您不能或不想使用
id
值,还有很多其他方法可以查找元素 — getElementsByTagName,然后通过其名称
等方便的参考资料:
You can hook the
click
event on both of the radio buttons, and then use thechecked
property of the one you're interested in to determine the visibiilty of thediv
via its.style.display
property ("none" for hidden, "" for default [block]).There are a variety of ways you can access the DOM elements for the radio buttons and
div
. One of the easiest is if you give themid
values:Then it's simply (live example):
Ensure that that script is at the end of the
body
element, or wrap it in awindow.onload
or similar handler.But if you can't or don't want to use
id
values, there are a lot of other ways to find the elements — getElementsByTagName and then find them by theirname
, etc.Handy reference material:
这直接出自我的脑海,没有测试过,但我认为它应该可以解决问题
This is straight out of my head, didn't test it but i think it should do the trick
通过事件处理,您可以获得更通用的解决方案,适用于多种情况。
问候。
With event handling you have a more generic solution, valid for more than one case.
Regards.
为每个输入元素添加和 ID:
使用 javascript 引用每个单选按钮,并根据其状态分配可见性:
Add and Id to each on the input elements:
With javascript reference each of the radio button, and assign the visibility according to their status:
这是您需要的代码:
Here is the code you need:
它有点长,但很有效。 -- >现场演示<
It is a little bit long but it works. -- > Live Demo <