如何获取单选按钮的文本(不是值) [英] How do I get the text of a radio button (not the value)

查看:243
本文介绍了如何获取单选按钮的文本(不是值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以得到一个单选按钮的值属性,但是我发现很难得到单选按钮的文本。



下面。它有3个单选按钮,并尝试提醒第一个单选按钮的值,这是红色,然后trys提醒单选按钮苹果,但失败的文本。


$ b $获取几乎任何元素的文本可以用elem.childNodes [0] .nodeValue完成。为什么它不适用于radiobuttons?

 <!DOCTYPE html PUBLIC -  // W3C // DTD XHTML 1.0 Strict // ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> 
< html xmlns =http://www.w3.org/1999/xhtmlxml:lang =enlang =en>
< head>
< title> Radio Buttons< / title>
< style type =text / css>
< / style>
< script type =text / javascript>
function start(){
var rblist = document.getElementsByName(colors);
var elem = rblist [0];
alert(elem.value); // PRINTSRED
alert(elem.childNodes [0] .nodeValue); // THROWS ERROR
}
< / script>
< / head>
< body onload =start();>
< input type =radioname =colorsvalue =redchecked> apple< / input>
< input type =radioname =colorsvalue =blue> sky< / input>
< input type =radioname =colorsvalue =green> grass< / input>
< / body>
< / html>


解决方案

它不工作,因为没有这样的东西作为< input> 内的文本,这在XHTML中是非法的。它必须是:



< input type =radioname =colorsvalue =redid =radio1checked = checked/>< label for =radio1> apple< / label>



然后你可以查找文本在< label> 内。


I know I can get the "value" attribute of a radiobutton but I'm finding it strangely difficult to get the text of the radiobutton.

Consider the example below. It has 3 radiobuttons and tries to alert the value of the first radio button, which is "red" and then trys to alert the text of the radiobutton, "apple" but that fails.

Getting the text of almost any element can be done with elem.childNodes[0].nodeValue. Why doesn't it work for radiobuttons?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<title>Radio Buttons</title>
<style type="text/css">
</style>
<script type="text/javascript">
function start(){
  var rblist = document.getElementsByName("colors");
  var elem = rblist[0];
  alert(elem.value); // PRINTS "RED"
  alert(elem.childNodes[0].nodeValue); //THROWS ERROR
}
</script>       
</head>
<body onload="start();">
<input type="radio" name="colors" value="red" checked>apple</input>
<input type="radio" name="colors" value="blue">sky</input>
<input type="radio" name="colors" value="green">grass</input>
</body>  
</html>

解决方案

It doesn't work because there is no such thing as text inside an <input> like that -- that's illegal in XHTML. It must be:

<input type="radio" name="colors" value="red" id="radio1" checked="checked" /><label for="radio1">apple</label>

Then you can look for the text inside the <label>.

这篇关于如何获取单选按钮的文本(不是值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆