2009-08-20 32 views
2

我知道我可以獲得單選按鈕的「值」屬性,但我發現奇怪地難以獲取單選按鈕的文本。如何獲取單選按鈕的文本(不是值)

考慮下面的例子。它有3個單選按鈕,並嘗試提醒第一個單選按鈕的值爲「紅色」,然後嘗試提醒單選按鈕文本「apple」的文本,但是失敗。

獲取幾乎任何元素的文本都可以用elem.childNodes [0] .nodeValue完成。爲什麼它不適用於單選按鈕?

<!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> 

回答

10

它不工作,因爲作爲一個<input>像這裏面的文字沒有這樣的事 - 在XHTML是非法的。它必須是:

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

然後,你可以查找<label>內的文本。

+0

+1 - 第二次我見過有人把今天的文字中''元素,有趣 – 2009-08-20 20:15:38

+0

+1 - 我承認我甚至不知道這是可能的。 ;)第一次看到像這樣的東西。儘管如此,無論如何,這個價值都可以被檢索(請參閱我的回答)。 – 2009-08-20 20:18:52

4
elem.nextSibling.nodeValue.replace('\n', '') 

的更換是擺脫換行符(可能在不同的操作系統,我運行Windows不同)字符是有某種原因。

1
<form id="myForm"> 
    <ul> 
     <li><input type="radio" name="colors" value="red">apple</li> 
     <li><input type="radio" name="colors" value="blue">sky</li> 
     <li><input type="radio" name="colors" value="green">grass</li> 
    </ul> 
</form> 

<script> 
(function(){ 
    var form = document.getElementById("myForm"); 

    var colorFields = form.elements["colors"]; 

    alert(colorFields[0].nextSibling.data); //alerts the text apple not the value red. 
}); 
0

我加了這個答案,因爲以前沒有完整的解決方案。
下面代碼使用了兩個原型函數從Array對象:

  1. forEach添加點擊事件監聽器用於每個無線電節點

  2. filter檢索檢查無線電節點

作爲RadioNodeList沒有內置這些​​功能。

var rblist = document.getElementsByName("colors");; 
 

 
[].forEach.call(rblist, function(e) { 
 
    e.addEventListener('click', showText, false) 
 
}); 
 

 
function showText() { 
 
    var rb = [].filter.call(rblist, function(e) { 
 
    return e.checked; 
 
    })[0]; 
 
    console.log(rb.nextElementSibling.innerText); 
 
};
<input type="radio" name="colors" value="red" /><label>apple</label> 
 
<input type="radio" name="colors" value="blue" /><label>sky</label> 
 
<input type="radio" name="colors" value="green" /><label>grass</label>