Jquery Use Image As CheckBox

前端 未结 6 1068
情话喂你
情话喂你 2021-01-07 08:59

I am in pursuit of implementing images as checkboxes. For now I am trying out a sample. The code below contains a simple image with a submit button next to it. On clicking t

6条回答
  •  走了就别回头了
    2021-01-07 09:34

    Click doesn't work like that, you can't toggle two functions. You must use an if statement like this

    $('#blr').click(function () {
        var chk = $('#imgCheck').get(0);
        if (!chk.checked) {
            $(this).css('border', 'solid 2px red');
            $('#imgCheck').prop('checked', true);
        } else {
            $(this).css('border', 'none');
            $('#imgCheck').prop('checked', false);
        }
    });
    

    DEMO

    You could shorten the code even more like this

    $('#blr').click(function () {
        var chk = $('#imgCheck').get(0);
            $(this).css('border', !chk.checked?'solid 2px red':'none');
            $('#imgCheck').prop('checked', !chk.checked);
    });
    

    DEMO

提交回复
热议问题