내가 강력하게 HTML에서 자바 스크립트를 제거하고, 결합 자바 스크립트를 사용하는 것이 좋습니다하려는 이벤트 처리 (더 쉽게 유지 보수 코드를 만들고, HTML을 통해 업데이트/변경하기 위해 사냥 할 필요가 없으므로; 그것은 모두 당신이 구현하는 JavaScript 파일/라이브러리에 있어야합니다). 다음 자바 스크립트와
<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>
:
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 그건 내가 다음 HTML을 제안 거라고 말했다.
또한, 나는 label
(텍스트 자체)를 클릭하면 해당 텍스트 관련 input
을 확인 할 수 있도록하기 위하여, 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합니다.
그것은 예를 들어, 색상으로 선택을 연결하는 자바 스크립트 객체를 사용할 수도 있습니다
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.
Miss-spelled attribute – mplungjan