jquery单击隐藏的复选框

时间:2016-05-13 07:59:52

标签: javascript jquery html css

我正在尝试为网站制作彩色滤镜。我想要删除可见的复选框(我有工作),删除标签等。只留下一个背景颜色< - 这一切都有效。但现在我不知道如何使这些div的点击能够,因为输入字段是隐藏的。有没有办法在jQuery中解决这个问题?

这是我的代码:

function onDataReceived(data) {
        $.each(data.colorInfo, function(key, colorInfo) {
            var inputElement = $("input[name^=filter][value="+colorInfo.id+"]").css("display", "none");
            var labelElement = $('label[for^=filter]').remove();
            var div  = inputElement.parent();

            div.attr('class', 'myclass_'+colorInfo.id);
            div.css("background-color", colorInfo.colorCode);
            div.css("width", "15px");
            div.css("height", "15px");
            div.css("display", "inline-block");
            div.css("marginLeft", "5px");
            div.css("marginBottom", "5px");
            //console.log(colorInfo);
        });
    }

    $(document).ready(function () {
        var url = 'myapi.json';
        $.get(url, onDataReceived);
    });

HTML:

<div class="filter_3">
    <input name="filter[]" value="152194" type="checkbox"/>
    <label for="filter_152194">Rood</label>
</div>
<div class="filter_4">
    <input name="filter[]" value="152196" type="checkbox"/>
    <label for="filter_152196">Blauw</label>
</div>
<div class="filter_5">
     <input name="filter[]" value="152198" type="checkbox"/>
     <label for="filter_152198">Oranje</label>
</div>

1 个答案:

答案 0 :(得分:2)

假设点击div后会调用一个函数:

function onDataReceived(data) {
    $.each(data.colorInfo, function(key, colorInfo) {
        var inputElement = $("input[name^=filter]  [value="+colorInfo.id+"]").css("display", "none");
        var labelElement = $('label[for^=filter]').remove();
        var div  = inputElement.parent();

        div.attr('class', 'myclass_'+colorInfo.id);
        div.css("background-color", colorInfo.colorCode);
        div.css("width", "15px");
        div.css("height", "15px");
        div.css("display", "inline-block");
        div.css("marginLeft", "5px");
        div.css("marginBottom", "5px");
        /* Added Lines */
        div.css("pointer-events", "auto"); //Just in case, but it's probably not necessary 
        div.css("cursor", "pointer"); //It's nice to have
        div.on('click', function() { //This is a click event delgated to the div
            // Whatever code is needed when div is clicked
        });
        //console.log(colorInfo);
    });
}

$(document).ready(function () {
    var url = 'myapi.json';
    $.get(url, onDataReceived);
});