[英]Change class and ID when a checkbox is clicked with jQuery
I have a checkbox on a html page which, when its checked I want to change the ID of one div and the class of another. 我在html页面上有一个复选框,当选中它时,我想更改一个div的ID和另一个div的类。
This is the code that I wrote to do it: 这是我编写的代码:
HTML: HTML:
<li><input type="checkbox" name="x" value="1" class="home6" /> Check this</li>
JQuery: JQuery的:
$(function(){
if ($('.home6').is(':checked')) {
$('.hider2').addClass('.hiderx').removeClass('.hider2');
$('#next1').attr('id','next4');
};
};
However this has no effect on my HTML. 但是,这对我的HTML没有影响。
I have tried debugging in the console but it throws no errors. 我曾尝试在控制台中进行调试,但不会引发任何错误。
I don't think the event is ever getting triggered as I have tried adding an alert into the if statement, however, having read the documentation for the :checked selector but this code seams to be right. 我认为该事件从未触发过,因为我尝试将警报添加到if语句中,但是,在阅读了:checked选择器的文档后,此代码似乎是正确的。
You should be having a change
OR click
event binded to your checkbox to execute your script. 您应该将
change
或click
事件绑定到您的复选框以执行脚本。
and in you code dot(.) in addClass
and removeClass
is incorrect 并且您在
addClass
和removeClass
代码dot(。)不正确
Try this: 尝试这个:
<li><input type="checkbox" name="x" value="1" class="home6" /> Check this</li>
And the respective jQuery code: 以及相应的jQuery代码:
$(function(){
$('.home6').on('change', function() {
if($(this).is(':checked'))
{
$('.hider2').addClass('hiderx').removeClass('hider2');
$('#next1').prop('id', 'next4');
}
});
});
Try this :- 尝试这个 :-
$(function(){
$($('.home6').change(function(){
if ($(this).is(':checked')) {
$('.hider2').addClass('hiderx').removeClass('hider2');
$('#next1').attr('id','next4');
};
};
});
It is working: http://jsfiddle.net/balintbako/KK2Xr/ 它正在工作: http : //jsfiddle.net/balintbako/KK2Xr/
if ($('.home6').is(':checked')) {
$('.hider2').addClass('hiderx').removeClass('hider2');
$('#next1').attr('id','next4');
};
How are you calling the function? 您如何调用该函数? You need to make that an action handler or call it on document.ready as it is in the fiddle.
您需要使其成为一个动作处理程序,或者像在小提琴中一样在document.ready上对其进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.