我有我的複選框列表複選框像以下:複選框檢查,未經檢查的事件的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的這個樣子,只是爲了檢查,如果它去反應,或者任何東西:
$('.check-brand').click(function() {
alert("Checkbox checked");
});
但是,當我點擊複選框沒有任何反應。我究竟做錯了什麼?
編輯,夥計們,我創建$。員額後,這個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();
});
});
也許是因爲在之後的jQuery .post的$調用生成的HTML的事實,這就是爲什麼它不」的原因t觸發事件?
雖然你應該真的使用'change'事件來做到這一點,你的代碼在技術上應該工作。可能有數百個原因,它沒有。你有沒有包含jQuery?你在document.ready處理程序中運行你的代碼嗎?控制檯中是否有錯誤? –
是的,我已經包含jQuery ...我已經測試了一些其他按鈕和鏈接,它的工作原理很好......也許問題是因爲我在$ .post調用完成後創建了這個HTML ?像下面這樣:我得到一個JSON數組...然後我以HTML的形式重新構建它...我已經更新了我的問題,供您查看。請問您可以看一下嗎? – perkes456
在這種情況下的問題是因爲您在加載DOM後追加元素,所以您需要一個委託事件處理程序。我給你添了一個答案。 –