[英]How do I get the label of the selected radio button using javascript
[英]In JavaScript, how do I make it so hovering over the label will output in a p tag the value of the radio button?
假设我有一个带有单选按钮的列表。 如何使鼠标悬停在标签上,将单选按钮的值写入HTML到<p>
标记中?
可以这么说:
o Option One
将鼠标悬停在选项一上会将单选按钮的值写入下面的<p>
标记中。
我的代码在下面,它将无法正常工作。 如果用户单击其他单选按钮,则应该明显更新。
function showDegree() {
var degreeOptions = document.getElementsByName('degree');
var degreeChoice;
var i;
for (i = 0; i < degreeOptions.length; i++) {
if (degreeOptions[i].checked) {
degreeChoice = degreeOptions[i].value;
}
}
document.getElementById('degreeOutput').innerHTML = degreeChoice;
}
您将不得不使用一个Event,您想到的是Hover
这个词(主要用于样式设置),但在这种情况下,您需要考虑onmouseover
这个词(用于操作...事件)。
假设您有以下内容:
<input type=radio value="val1">Option 1
<p id=optDisplay></p>
您必须在每个input
以下内容:
<input type=radio value="val1" onmouseover="document.getElementById( 'optDisplay').textContent = this.value;">Option 1
请注意,只有当鼠标指针悬停在单选元素上方时,它才会发生,只有小圆圈,如果您将文本“选项1”指向鼠标,则不会起作用。 如果要完成此操作,可以将input
元素和文本包装在另一个标签(例如span or div
,而该标签必须具有如下onmouseover
:
<span onmouseover="document.getElementById( 'optDisplay').textContent = this.firstChild.value;"><input type=radio value="val1"> Option 1</span>
onmouseover改变了一点,至于您单击“更新”时所说的,您不必做任何事情,就好像您单击鼠标一样,鼠标将悬停在它上面,并且只要您不指向其他任何选项会保持那样。
如果单击一次以阻止任何其他更改,则将变得有些棘手,但是快速考虑一下,例如可以添加另一个事件onclick
来删除<P>
的ID,然后在此之后,如果您指针其他选项,它们将不会找到<P>
,没有更新。
尝试如果
.checked == true
要么
如果.checked =='选中'
-很抱歉,我习惯于围绕jQuery进行编码,以至于我忘记了执行本机的正确方法...在那一点上,如果性能不是问题,您可能要考虑使用jquery,这很简单在jQuery中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.