如何使用输入复选框检查特定图像

how to check a specific image with input checkbox

本文关键字:图像 检查 复选框 何使用 输入      更新时间:2023-09-26

我有这段代码,我还在修改。但我还是很难过。我是jquery新手。我计划使图像的多个复选框。请检查我的代码。这行不通。我的示例代码是两个复选框。我打算把它放在数组上,这样我就可以把两个以上的复选框与图像。而不是在每个复选框中编写jquery代码。

这是我的代码

html

<form id="form1">
    <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr" class="" />
    <input type="checkbox" id="imgCheck[]" name="imgCheck" value="barney" />
    <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr" class="" />
    <input type="checkbox" id="imgCheck[]" name="imgCheck" value="barney2" />
    <input type="submit" value="Submit" />
</form>
jquery

$('img').on('click', function(){
        var $$ = $(this)
        if( !$$.is('.checked')){
            $$.addClass('checked');
            $('input[id=imgCheck]').prop('checked', true);
        } else {
            $$.removeClass('checked');
            $('input[id=imgCheck]').prop('checked', false);
        }
    })

风格
.checked {border:solid 2px red}

Try

$('img').on('click', function () {
    var $$ = $(this)
    //toggle the checked state
    $$.toggleClass('checked');
    //set the next checkbox's state in synch with the checked state of the image
    //from the given markup we can assume that an image will always be related to the next sibling element which will be checkbox
    $$.next('input').prop('checked', $$.hasClass('checked'));
})

演示:小提琴

  • toggleClass ()
  • hasClass ()
  • next ()