我強烈建議從你的HTML刪除你的JavaScript,並使用JavaScript綁定的事件處理(這使得更容易維護的代碼,因爲你不必通過HTML尋找更新/改變任何東西;它應該全部位於您實現的JavaScript文件/庫中)。這就是說,我建議以下HTML:
<div id="genre">What do you bust a move to?
<form name="music" method="post" action="#">
<input type="radio" name="music" value="radio"/>Blues
<input type="radio" name="music" value="radio" />Rock
<input type="radio" name="music" value="radio" />Pop</form>
</div>
用下面的JavaScript:
function changeColour (e) {
// e.target is the element that triggered the event we're reacting to:
var el = e.target;
/* el.nextSibling.nodeValue is the text of the next sibling-node,
toLowerCase() turns that text into lower-case,
[0] gets the first letter of that text:
*/
switch (el.nextSibling.nodeValue.toLowerCase()[0]) {
case 'b' :
// 'this' is the element that's handling the event (the div):
this.style.backgroundColor = '#00f';
break;
case 'r' :
this.style.backgroundColor = '#f00';
break;
case 'p' :
this.style.backgroundColor = '#f0f';
break;
}
}
/* gets the element with the id of 'genre', and adds a listener to that
element, listening for the change event, and triggering the 'changeColour'
function when it's detected:
*/
document.getElementById('genre').addEventListener('change', changeColour, true);
JS Fiddle demo。
此外,我建議包裹input
元素與label
元素,以便點擊label
(文本本身)能夠檢查相關input
該文本:
<div id="genre">What do you bust a move to?
<form name="music" method="post" action="#">
<label>
<input type="radio" name="music" value="radio" />Blues</label>
<label>
<input type="radio" name="music" value="radio" />Rock</label>
<label>
<input type="radio" name="music" value="radio" />Pop</label>
</form>
</div>
JS Fiddle demo。
它也可以使用JavaScript對象的選擇顏色,關聯例如:
function changeColour(e) {
// sets the letter-colour options:
var colorMap = {
'b' : '#00f',
'r' : '#f00',
'p' : '#fof'
};
var el = e.target,
checked = el.nextSibling.nodeValue.toLowerCase()[0];
/* if the relevant letter is in the colorMap object
(and generates a truthy value), we set the background-color
to whatever is retrieved:
*/
if (colorMap[checked]){
this.style.backgroundColor = colorMap[checked];
}
}
document.getElementById('genre').addEventListener('change', changeColour, true);
JS Fiddle demo。
拼寫錯誤的屬性 – mplungjan