我的页面中有一组单选按钮。在更改中我想知道哪个按钮未选中但在onchange
事件$(this)
上指的是新选择的按钮是否有任何方法可以获取旧的未选择按钮?
window.old = null;
$('.radio').change(function(){
alert($(this).val()); // this is the selected
alert($(window.old).val()); // this is the old one
})
答案 0 :(得分:2)
只需将最后点击的广播保存到变量
即可window.old = null;
$(document).ready(function() {
window.old = $('.radio:checked');
});
$('.radio').change(function() {
alert($(this).html());
if (window.old) {
alert($(window.old).html());
}
window.old = this;
})
答案 1 :(得分:1)
单击(更改前)保存单选按钮,然后阅读新单击上的单选按钮,代码如下:
window.old = null;
$('.radio').click(function () {
// Store the current radio on click, before it changes
window.old = this;
}).change(function() {
// Do something with the old radio value after the change
console.log('previous radio:', window.old);
});
答案 2 :(得分:0)
没有Globals
$('input[type="radio"]').click(
function (e)
{
var me = $(this);
var grp = $("input[type='radio'][name='" + me.attr('name') + "']");
if (me.val() === me.data('last-val'))
{
me.prop('checked', false);
grp.data('last-val', null);
}
else
{
grp.data('last-val', me.val());
}
}
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<fieldset >
<legend> Group 1 </legend>
<label>
<input type="radio" name='grp1' value='1'/>
You can select me
</label>
<label>
<input type="radio" name='grp1' value='2'/>
But you can
</label>
<label>
<input type="radio" name='grp1' value='3'/>
Change your idea either
</label>
</fieldset>
<fieldset >
<legend> Group 2 </legend>
<label>
<input type="radio" name='grp2' value='1'/>
Just give another click
</label>
<label>
<input type="radio" name='grp2' value='2'/>
But remember, for this work
</label>
<label>
<input type="radio" name='grp2' value='3'/>
Values must be unique in each group
</label>
</fieldset>
&#13;