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

标签 javascript jquery

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

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
    }   
})

最佳答案

它在您的 prop() 方法中。现在您将 checked 属性指定为 false,而实际上您应该只检查是否为 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

关于javascript - 使用图像作为复选框占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17331896/

相关文章:

jquery - 条形图插件 - 使每个条形图都可点击(每个条形图都有不同的链接)

javascript - mozilla 中的 KeyCode 出现错误

javascript - 如何将grails json数据作为指令属性值传递给angularjs指令

javascript - 如何根据用户选择更改日期格式?

javascript - 将新属性添加到另一个数组中的现有对象数组

javascript - jQuery Keydown 事件使球消失

javascript - jQuery 无法在 Firefox 中加载

javascript - 使用 Jquery 检查时通过复选框更改背景颜色

javascript - 如果没有返回语句,Flask session 不会保留由 ajax 设置的值

javascript - 停止在 JSTree 中的 Ajax 加载/延迟加载中加载节点