[英]Issue with checkbox onchange jquery
我在最近的代碼中遇到了奇怪的事情。
我有一個動態生成的列表,其中每一行都包含一個復選框。 我的意圖是,如果復選框更改並且得到確認,我的數據庫將被更新。
問題是,它在我第一次更改時確實有效。 但是以下嘗試卻沒有。 但是,如果刷新頁面,則在我第一次更改時它可以再次工作。
它必須是一些JavaScript的東西。
$(':checkbox').change(function() {
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
$.post( "handler.php", { handler: '18', value: variable}, location.reload());
}
});
PS:每次觸發並且值更改時,也會提醒“變量”。
你們能幫我解決嗎?
提前致謝。
編輯:非常感謝所有的答案。 除了對事件委托的理解之外,幫助我的是,它與單擊事件一起使用效果更好。 我仍然會嘗試了解onblur觸發onchange的意義,但是目前,保持onchange並沒有幫助我。
如前所述,行是動態生成的,您需要使用事件委托,如下所示:
$(document.body).on("change",":checkbox", function() {
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
$.post( "handler.php", { handler: '18', value: variable}, location.reload());
}
});
如果$(document.body)
或$(document)
是目標元素的容器,則可以使用最接近的父元素/容器,而不是$(document.body)
或$(document)
。
通過事件委托,我們可以將單個事件偵聽器附加到父元素,該元素將為與選擇器匹配的所有后代觸發,無論這些后代現在存在還是將來添加。
對於動態創建的DOM元素:
$(':checkbox').on("change",function() {
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
$.post( "handler.php", { handler: '18', value: variable}, location.reload());
}
});
更好的是:
$(document.body).on("change", ":checkbox" ,function() { // you can replace with wrapping container ID
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
$.post( "handler.php", { handler: '18', value: variable}, location.reload());
}
});
使用$( "input:checkbox" )
工作小提琴 : http : //jsfiddle.net/h3ar8/
$(document).ready(function(){
$('input:checkbox').change(function() {
if (confirm("Does the status of this survey really changed?")) {
variable = $(this).val();
alert(variable);
}
});
});
根據Jquery http://api.jquery.com/checkbox-selector/,您應該使用$( "input:checkbox" )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.