我有一个广播组,其中包含与每个按钮关联的下拉列表。当选择其中一个列表时,我希望选择与所选列表关联的单选按钮。我有这个工作,但在第二次或第三次选择后,它停止工作。我正在使用的代码如下。有人请看一下吗?
$(function() {
$(".by_email").change(function() {
$('input:radio[name="group1"][value="By Email"]').attr('checked', true);
});
$(".by_id").change(function() {
$('input:radio[name="group1"][value="By ID"]').attr('checked', true);
});
$(".by_name").change(function() {
$('input:radio[name="group1"][value="By Name"]').attr('checked', true);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div style="display:inline-block"><input type="radio" name="group1" id="by_email" value="By Email">By Email:</div>
<div style="display:inline-block">
<select class="by_email">
<option>choose email</option>
<option>me.com</option>
<option>you.com</option>
</select>
</div>
<div style="display:inline-block">
<select class="by_email">
<option>choose next email</option>
<option>us.com</option>
<option>them.com</option>
</select>
</div>
</div>
<div>
<div style="display:inline-block"><input type="radio" name="group1" id="by_id" value="By ID" checked=checked>By ID:</div>
<div style="display:inline-block">
<select class="by_id">
<option>choose id</option>
<option>1</option>
<option>2</option>
</select>
</div>
<div style="display:inline-block">
<select class="by_id">
<option>choose next id</option>
<option>11</option>
<option>22</option>
</select>
</div>
</div>
<div>
<div style="display:inline-block"><input type="radio" name="group1" id="by_name" value="By Name">By Name:</div>
<div style="display:inline-block">
<select class="by_name">
<option>choose name</option>
<option>bob</option>
<option>sally</option>
</select>
</div>
<div style="display:inline-block">
<select class="by_name">
<option>choose next name</option>
<option>emma</option>
<option>fred</option>
</select>
</div>
</div>
&#13;
答案 0 :(得分:2)
如果您首先取消选中其他方框,则无效;
$(function () {
$(".by_email").change(function () {
$('input:radio[name="group1"]').attr('checked', false);
$('input:radio[name="group1"][value="By Email"]').attr('checked', true);
});
$(".by_id").change(function () {
$('input:radio[name="group1"]').attr('checked', false);
$('input:radio[name="group1"][value="By ID"]').attr('checked', true);
});
$(".by_name").change(function () {
$('input:radio[name="group1"]').attr('checked', false);
$('input:radio[name="group1"][value="By Name"]').attr('checked', true);
});
});
正如评论中所指出的,这也可以用prop取代attr;
$(function () {
$(".by_email").change(function () {
$('input:radio[name="group1"][value="By Email"]').prop('checked', true);
});
$(".by_id").change(function () {
$('input:radio[name="group1"][value="By ID"]').prop('checked', true);
});
$(".by_name").change(function () {
$('input:radio[name="group1"][value="By Name"]').prop('checked', true);
});
});