繁体   English   中英

jQuery中的复选框检查和未检查事件

[英]Checkbox check and unchecked event in jquery

我的复选框列表中有复选框,如下所示:

<div class="pop-mission-to">
    <label>
        <input class="check-brand" type="checkbox" name="" value="1" data-id="1">
    </label>
</div>

<div class="pop-mission-to">
    <label>
        <input class="check-brand" type="checkbox" name="" value="2" data-id="2">
    </label>
</div>

我已经在jQuery中创建了一个on click函数,就像这样,只是为了检查它是否会做出反应或执行任何操作:

$('.check-brand').click(function() {
    alert("Checkbox checked");
});

但是,当我单击复选框时,没有任何反应。 我究竟做错了什么?

编辑,伙计们,我在$ .Post之后创建此HTML,如下所示:

$('.check-user').click(function() {
    var $this = $(this);
    var user_id = $this.attr('value');
    var brandContainer = $this.closest('.pop-state').siblings('.pop-brands');
    brandContainer.html('<p style="margin: 10px !important;">Processing... </p>');
    $.post('/user/usersBrands', { userId: user_id } , function(data) {
        console.log(data);
        var brands = JSON.parse(data);
        var container = $('<div class="pop-mission-co" />');

        brands.forEach(function (brand, index) {
            var isRegisteredToBrand = null;
            console.log(brand.userId);
            if(brand.userId==null)
            {
                isRegisteredToBrand = false;
             }
            else{
                isRegisteredToBrand = true;
            }
            console.log(isRegisteredToBrand);
            container.append(buildBrand(brand.id, brand.name, isRegisteredToBrand, index));
        });
        function buildBrand(id, name, isActive, index) {
            var isChecked = isActive ? 'checked="checked"' : ' ';
            return $(
                '<div class="pop-mission-to">' +
                    '<label>' +
                        '<input class="check-brand"' +
                            isChecked +
                            'type="checkbox"' +
                            'name=""' +
                            'value="' + id + '"' +
                            'data-id="' + index + '">'
                                + name +
                    '</label>' +
                '</div>'
            );
        }
        brandContainer
            .children('p').remove();
        brandContainer
            .html(container)
            .find('.pop-mission-co').show();
    });
});

也许是事实,因为HTML是在jquery中的$ .post调用之后生成的,这就是它不触发事件的原因?

问题是因为在DOM加载后要动态追加元素,所以需要使用委托事件处理程序。 另请注意,您应该在复选框上使用change事件,而不是click 尝试这个:

$('.check-user').click(function() {
    var $this = $(this);
    var user_id = $this.attr('value');
    var brandContainer = $this.closest('.pop-state').siblings('.pop-brands');

    brandContainer.on('change', '.check-brand', function() {
        alert("Checkbox checked");
    });

    // the rest of your code...
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM