假设一组4个无线电盒,其中第一个被检查。然后用户点击第3个单选框。有没有办法知道第一台收音机是最后一台收音机?
答案 0 :(得分:2)
如果绑定到mousedown
事件而不是click
,则在事件侦听器运行时,已检查的无线电还没有更改:
<fieldset id="radios">
<input type="radio" name="rad" value="1"> option 1<br>
<input type="radio" name="rad" value="2"> option 2<br>
<input type="radio" name="rad" value="3"> option 3<br>
</fieldset>
var radios = document.getElementById('radios');
radios.addEventListener('mousedown', function(e) {
var clicked = e.target;
var current = document.querySelector('input[name=rad]:checked');
});
注意:此解决方案是IE8 +,请参阅http://caniuse.com/#search=queryselector
答案 1 :(得分:2)
1)声明一个全局变量
var currentlySelected = null;
2)将处理程序附加到所有单选按钮的click事件。
function radioButtonOnClickEvent() {
if (currentlySelected === null) {
// nothing has been selected yet
currentlySelected = radioBoxThatWasJustClicked;
} else if (currentlySelected === theThirdRadioButton) {
//your logic here
currentlySelected = radioBoxThatWasJustClicked;
}
}
答案 2 :(得分:1)
是的,有办法做到这一点。我添加了您的代码和完成的脚本以获取最后一个选择单选按钮。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test webservices</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$('input[name="rad"]').click(function (e) {
if($(this).siblings('input[name="rad"]').hasClass('lastSelected'))
{
var lastSelectedButton = $('.lastSelected').val();
$(this).siblings('input[name="rad"]').removeClass('lastSelected');
$(this).addClass('lastSelected');
}
else
$(this).addClass('lastSelected');
});
});
</script>
</head>
<body>
<form action='xyz.php' method='get'>
<input type="radio" name="rad" value="1"> option 1<br>
<input type="radio" name="rad" value="2"> option 2<br>
<input type="radio" name="rad" value="3"> option 3<br>
<input type='submit' value='Go' id='submit' >
</form>
</body>
</html>
这是你问题的完美答案。您可以尝试使用此脚本的复制粘贴来实现它。