需求
<input type="radio" id="need" name="need" value="0" />啟用 <input type="radio" id="need" name="need" value="1" />禁用 <br /> <input type="text" value="hello"/> <input type="button" value="ok"/>
我想讓radio來控制下面的兩個控件的啟用與禁用
(不要說用checkbox,我是必須為了掩飾radio的功能)
嘗試
使用 change 事件似乎是可以的。
jquery的文檔中(http://api.jquery.com/change/)說,change事件在元素的值發生改變時觸發。
The change event is sent to an element when its value changes. This event is limited to<input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
但是change事件對radio並不湊效。StackOverflow上也有相關討論:
http://stackoverflow.com/questions/5831615/jquery-mobile-radio-group-change
http://stackoverflow.com/questions/964961/jquery-radio-onchange-toggle-class-of-parent-element
你可以很容易的測試一下
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<input type="radio" id="need" name="need" value="0" />啟用
<input type="radio" id="need" name="need" value="1" />禁用
<br />
<input type="text" value="hello"/>
<input type="button" value="ok"/>
<div id="log"></div>
<script type="text/javascript">
$(document).ready(function ()
{
$("#need").change(function ()
{
$("#log").append($("<p/>").text("fired"));
});
});
</script>
</body>
</html>
只有前一個radio選擇時才觸發change事件,非常奇怪。
分析
錯誤非常弱智,因為我是使用的 id 作為篩選器!重復id只能選中第一個!坑爹啊有木有!
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="needradio">
<input type="radio" id="need" name="need" value="1" />啟用
<input type="radio" id="need" name="need" value="0" />禁用
</div>
<input type="text" value="hello"/>
<input type="button" value="ok"/>
<div id="log"></div>
<script type="text/javascript">
$(document).ready(function ()
{
$("#needradio :radio").change(function ()
{
$("#log").append($("<p/>").text("fired"));
setEnable($(this).val()=="1");
});
});
function setEnable(b)
{
var ips = $("input").not(":radio").add("textarea");
if (b)
ips.removeAttr("disabled");
else
ips.attr("disabled", true);
}
</script>
</body>
</html>
