所以我正在尝试使用jquery来检测何时选中了复选框并取消选中(通过单击我应该添加的标签)来更改css属性。
以下是复选框代码的示例:
<div class="block" id="block_1">
<input type="checkbox" name="images" id="image_1" class="block_input" />
<label for="image_1" class="block_button" style="background-image:url(img/bnw/block_1bnw.png);">
<span>Label text</span></label>
</div>
这是我到目前为止只有一半工作的jQuery:
$('.block_button').click(function(){
var imgId = $(this).parent().attr('id');
if ($(this).siblings('.block_input').checked == true) {
$(this).css("background-image", "url(img/color/" + imgId + ".png)");
} else {
$(this).css("background-image", "url(img/bnw/" + imgId + "bnw.png)");
}
});
当您最初选中此框时,css会正确更改,但一旦取消选中,则无法更改。我已经尝试在点击时记录.checked方法的结果,即使取消选中它也似乎仍然存在。那么一旦用户决定取消选中该框,我怎样才能让else语句工作?
谢谢!
答案 0 :(得分:1)
我相信你的错误就在这里:
if ($(this).siblings('.block_input').checked = true) {
应该是==
而不是=
。事实上,你可以把它写成:
if ($(this).siblings('.block_input').checked) {
正在发生的事情:当该行投放时,您将checked
的值设置为true
。这会覆盖先前的checked
值。
修改:获得rudimentary working example (JSFiddle)需要进行一些更改。
更改复选框更改时要触发的事件,而不是从标签的角度更改。这也将抓住用户点击复选框本身,或通过其他方式(例如,通过键盘)更改复选框的状态。
$('.block_input').change(function(){
检查属性.checked
(有关详细信息,请参阅this SO answer),如下所示:
if ($(this).prop('checked')) {
现在复选框上已触发事件,您需要修改对标签的引用:
$(this).siblings('.block_button').css( ...
答案 1 :(得分:1)
JQuery对象没有“已检查”属性,因此永远不会评估为true。
要通过相应的JQuery对象访问HTML元素的属性,必须使用.prop()方法。或者,换句话说......
$('.block_button').click(function(){
var imgId = $(this).parent().attr('id');
if (! $(this).siblings('.block_input').prop('checked')) {
$(this).css("background-image", "url(img/color/" + imgId + ".png)");
} else {
$(this).css("background-image", "url(img/bnw/" + imgId + "bnw.png)");
}
});
注意,我还添加了一个“!”在if语句中,因为此函数在复选框的状态更改之前触发。因此,这里的状态与点击事件完成传播后的状态相反。
还有另一种方法可以做得更有意义:
$('.block_input').change(function(){
var imgId = $(this).parent().attr('id');
if ($(this).prop('checked')) {
$(this).siblings('.block_button').css("background-image", "url(img/color/" + imgId + ".png)");
} else {
$(this).siblings('.block_button').css("background-image", "url(img/bnw/" + imgId + "bnw.png)");
}
});
这样,您定义的函数会在输入更改后调用,而不是之前调用。如果用户点击复选框本身,它也会被触发,而不仅仅是它旁边的图像。 (如果您的用户在页面上跳转,这很有用)
希望这有帮助!