我讨厌匿名函数。虽然他们可以占有一席之地,但这主要是懒惰的编程,恕我直言。
这里有一些代码,希望您能更清楚地理解。
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('load', mInit, false);
function mInit()
{
var radioBtns = document.querySelectorAll("input[type=radio]");
var i, n = radioBtns.length;
for (i=0; i<n; i++)
{
var btnGroupName = radioBtns[i].getAttribute('name');
if (btnGroupName == 'yesNo')
radioBtns[i].addEventListener('change', onRbGroup1Change, false);
else if (btnGroupName == 'gender')
radioBtns[i].addEventListener('change', onRbGroup2Change, false);
}
}
function onRbGroup1Change()
{
document.getElementById('radioResult').innerHTML = "Value of chosen radio button is: " + this.value;
}
function onRbGroup2Change()
{
document.getElementById('radioResult2').innerHTML = "Gender of chosen radio button is: " + this.value;
}
</script>
<style>
</style>
</head>
<body>
<label>Yes<input type="radio" name="yesNo" value="afirmative"/></label>
<label>No<input type="radio" name="yesNo" value="negative"/></label>
<div id='radioResult'>You need to select a radio-button first!</div>
<label>Girl<input type="radio" name="gender" value="Female"/></label>
<label>Boy<input type="radio" name="gender" value="Male"/></label>
<div id='radioResult2'>You need to select a radio-button first!</div>
</body>
</html>