使用图像作为复选框占位符

时间:2013-06-26 23:03:48

标签: javascript jquery

基本上,当我选中/取消选中复选框时,我正在尝试交换图像,但我无法弄清楚为什么在第二次点击图像时“取消选中”永远不会发生(控制台永远不会打印“UNcheck it”)

HTML:

<div id="inventory">
    <div class="nav">
        <div class="categories">
            <input type="checkbox" name="category" value="top">
            <input type="checkbox" name="category" value="bottom">
            <input type="checkbox" name="category" value="shoes">
            <input type="checkbox" name="category" value="accessories">
            <input type="checkbox" name="category" value="hairstyles">
            <input type="checkbox" name="category" value="eyes">
            <input type="checkbox" name="category" value="heads">
            <input type="checkbox" name="category" value="skins">
            <input type="checkbox" name="category" value="avatars">
            <a href="#" class="placeholder top"></a>
            <a href="#" class="placeholder bottom"></a>
            <a href="#" class="placeholder shoes"></a>
            <a href="#" class="placeholder accessories"></a>
            <a href="#" class="placeholder hairstyles"></a>
            <a href="#" class="placeholder eyes"></a>
            <a href="#" class="placeholder heads"></a>
            <a href="#" class="placeholder skins"></a>
            <a href="#" class="placeholder avatars"></a>                
        </div>
    </div>
</div>


JS / jQuery的:

$('#inventory .nav .categories .placeholder').click(function(e){
    e.preventDefault();
    var category = $(this).attr('class').split(' ')[1]; //Grab second class of the clicked placeholder
    var relatedCheckbox = $('#inventory .nav .categories input[value="' + category + '"]'); //find the actual related checkbox
    if (relatedCheckbox.prop('checked', false)) { //if the related checkbox is unchecked...
        console.log('check it!');
        relatedCheckbox.attr('checked', 'checked') //check it!
    } else { //if it is already checked
        console.log('UNcheck it!');
        relatedCheckbox.removeAttr('checked'); //uncheck it
    }   
})

1 个答案:

答案 0 :(得分:3)

它在您的prop()方法中。现在,当您真正检查是否为假时,您将checked属性指定为false。

if (!relatedCheckbox.prop('checked')) {
    relatedCheckbox.prop('checked',true) // <--use this to check it
} else {
    relatedCheckbox.prop('checked',false) // <-- use this to uncheck it
} 

Example scenario