我强烈建议从你的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