[英]How to trigger event when a radio button is checked in jQuery
I tried doing this .So, when I click on the radio button, the code works but the radio button doesn't get checked and it remains normal. 我试图做这个 。所以,当我点击单选按钮,代码工作,但单选按钮没有得到遏制,它仍然正常。 How to solve this? 怎么解决这个?
<p>
<input id="play" class="rad" type='radio' name='a'/>
<input id="pause" class="rad" type='radio' name='a'/>
</p>
var output = $('h1');
var isPaused = false;
var time = 30;
var t = window.setInterval(function () {
if (!isPaused) {
time--;
output.text("0:" + time);
}
}, 1000);
//with jquery
$('.pause').on('click', function (e) {
e.preventDefault();
isPaused = true;
});
$('.play').on('click', function (e) {
e.preventDefault();
isPaused = false;
});
A few things: 一些东西:
Your selectors are wrong: $('.pause')
should either be $("#pause")
or $(".rad")
您的选择器是错误的: $('.pause')
应该是$("#pause")
或$(".rad")
Also, you are calling e.preventDefault()
inside click
. 此外,您在click
内部调用e.preventDefault()
。 This is preventing the default behavior of a click on a radio button, which is to check it. 这样可以防止点击单选按钮的默认行为,即检查它。
Updated jsFiddle for what I think you're trying to achieve, which is to let the radio buttons be a toggle for your timer: 更新了jsFiddle我认为你想要实现的目标,即让单选按钮成为你的计时器的切换:
var output = $('h1');
var isPaused = false;
var time = 30;
var t = window.setInterval(function() {
if(!isPaused) {
time--;
output.text("0:" + time);
}
}, 1000);
//with jquery
$('#pause').on('click', function(e) {
isPaused = true;
});
$('#play').on('click', function(e) {
isPaused = false;
});
$("input[type=radio]").change(function(){
if(this.checked)
{
alert("checked");
}
});
And if your radio button has id say play
then directly use #play
as selector ie $("#play").change()
. 如果你的单选按钮有id说play
那么直接使用#play
作为选择器即$("#play").change()
。
<input id="play" class="rad" type='radio' name='a' value="1"/>
<input id="pause" class="rad" type='radio' name='a' value="2"/>
var output = $('h1');
var isPaused = false;
var time = 30;
var t = window.setInterval(function() {
if(!isPaused) {
time--;
output.text("0:" + time);
}
}, 1000);
//with jquery
$('.rad').on('change', function(e) {
e.preventDefault();
if(this.value=='2')
isPaused = true;
else
isPaused = false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.