我的页面中有一组单选按钮。在更改时,我想知道哪个按钮未被选中,但onchange
事件$(this)
指的是新选择的按钮,有没有办法让旧的未选中按钮?
window.old = null;
$('.radio').change(function(){
alert($(this).val()); // this is the selected
alert($(window.old).val()); // this is the old one
})
我的页面中有一组单选按钮。在更改时,我想知道哪个按钮未被选中,但onchange
事件$(this)
指的是新选择的按钮,有没有办法让旧的未选中按钮?
window.old = null;
$('.radio').change(function(){
alert($(this).val()); // this is the selected
alert($(window.old).val()); // this is the old one
})
只需将最后点击的收音机保存到变量中,
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;
})
保存单击时的单选按钮(更改前),并在新的单击时读取单选按钮,代码如下:
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);
});
没有全局变量
$('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>