这是另一种方法,不涉及使用内联 onClick。出于这个原因,我将脚本移到了 body 标记的末尾,以便在我们开始在 JavaScript 中处理它们之前,这些元素在 DOM 中可用。代码注释解释了发生了什么。
香草 JavaScript
<html>
<head>
</head>
<body>
<form name="A" >
<span class="toggle-bg">
<input type="radio" name="toggle" value="off" >
<input type="radio" name="toggle" value="on">
<span class="switch"></span>
</span>
<input type="text" name="T1" value="A" disabled>
<input type="text" name="T2" value="B" disabled>
</form>
<script>
// First, get a collection of the radio inputs with the name 'toggle'
var toggles = document.getElementsByName('toggle');
// Loop through each radio input with the name 'toggle' and add an event listener
// to each toggle input so it knows what to do when a user clicks it.
for (var i = 0; i < toggles.length; i++) {
toggles[i].addEventListener('click', function(event) {
// Assign 'Allow' the value of the target. The target will be the radio
// input that the user clicks. The value is simply the value you have set
// above in your code - 'on' or 'off'.
var Allow = event.target.value;
// Check for the value of 'off' or 'on'
if (Allow === 'off') {
// Value is 'off', so disable the text inputs.
// document.GetElementsByName() returns an array of elements. Because of this,
// we have to use the [0] after we call it to get the first element in the array.
// Because each element must have a unique name, this will grab the correct text
// inputs to target.
document.getElementsByName('T1')[0].disabled = true;
document.getElementsByName('T2')[0].disabled = true;
} else {
// Value is 'on', so enable the text inputs.
document.getElementsByName('T1')[0].disabled = false;
document.getElementsByName('T2')[0].disabled = false;
}
}, false);
}
</script>
</body>
</html>
jQuery 解决方案
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('input:radio[name=toggle]').click(function(event) {
if (event.target.value == 'on') {
$('input:text[name=T1], input:text[name=T2]').removeAttr("disabled");
} else {
$('input:text[name=T1], input:text[name=T2]').attr("disabled", "disabled");
}
});
});
</script>
</head>
<body>
<form name="A" >
<span class="toggle-bg">
<input type="radio" name="toggle" value="off" >
<input type="radio" name="toggle" value="on">
<span class="switch"></span>
</span>
<input type="text" name="T1" value="A" disabled>
<input type="text" name="T2" value="B" disabled>
</form>
</body>
</html>