我为任务管理器应用程序构建 UI。我的页面上有一个按钮获取所有任务
。当用户单击此按钮时,他会列出所有任务。每个任务都有状态为 boolean done = true/false
的复选框。当任务打印在页面上时,任务的每个复选框都有根据任务状态的状态。
当用户点击复选框时,向服务器发送ajax请求,其中包含两个值:任务的id
和done
的新值。
但我有问题:当我单击复选框以更改完成
状态时,然后调用所有复选框而不是我单击的一个复选框。
帮我解决这个问题。谢谢。
这是代码:
$(document).ready(function(){
//button id.
$("#get_all_task_but").click(function(){
// URL of servlet.
$.ajax({
url : 'get_all_tasks',
type : "post",
success : function (data) {
var data = JSON.parse(data);
$.each( data, function( key, value ) {
//insert HTML into DOM here
var checkboxName = 'checkbox'+value['id'];
var checkboxValue = value['desc'];
var checkboxHtml = '<input type="checkbox" name="'+checkboxName+'" value="'+checkboxValue+'" />';
$('#all_tasks').append(checkboxHtml);
});
$('input[type="checkbox"]').on('change', function(e)
{
//info on which checkbox is click in 'this' and the event object
//$(this) to get the checkbox as jQuery object
console.log('Send to server', this, e);
});
}
});
});
});
HTML
<body>
<form id="result_from_server">
<input name="data" type="text">
<input type="submit" value="send">
</form>
<div id="resp"></div>
<div>
<input id="get_all_task_but" type="button" value="Get all task" />
<ul id="all_tasks">
</ul>
</div>
</body>
最佳答案
不要监听正文上的click事件,而是监听复选框上的change事件:
success : function (data) {
var data = JSON.parse(data);
$.each( data, function( key, value ) {
//insert HTML into DOM here
var checkboxName = 'checkbox'+value['id'];
var checkboxValue = value['desc'];
var checkboxHtml = '<input type="checkbox" name="'+checkboxName+'" value="'+checkboxValue+'" />';
$('#all_tasks').append(checkboxHtml);
});
$('input[type="checkbox"]').on('change', function(e)
{
//info on which checkbox is click in 'this' and the event object
//$(this) to get the checkbox as jQuery object
console.log('Send to server', this, e);
});
}
也许通过类而不是$('input[type="checkbox"]')来定位复选框。
。
如果您想测量值是否更改,请不要使用点击事件。这就是更改事件的用途。
关于javascript - 如何关联函数和复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45145239/