我的复选框列表中有如下复选框:
<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 中创建了一个像这样的点击函数,只是为了检查它是否会使用react或其他什么:
$('.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 后动态附加元素,因此您需要使用委托(delegate)事件处理程序。另请注意,您应该在复选框上使用 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...
});
关于javascript - jquery中的复选框选中和未选中事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37697185/