gpt4 book ai didi

javascript - jQuery post 和 OnClick 问题

转载 作者:行者123 更新时间:2023-11-30 17:38:40 27 4
gpt4 key购买 nike

我的 jQuery 遇到了问题。基本上我选择了一个表单提交并使用 jQuery Post 到我的 api。现在,如果找到项目,each用于创建一个包含显示数据的表格,然后用户可以访问该表格。

$('#update-postcode').submit(function(){
$('#location-set-content').html('');
event.preventDefault();

var form = $(this).serialize();

// Request
$.post('/api/postcode/check',
form,
function(data) {
// check response
$.each(data,function(k,v) {
var status = $.trim(data.status);

if(parseInt(status) < 1){
// remove the status
delete data.status;
$('#location-set-content').html('<h1 class="text-center">Unable to Find Location :(</h1>');
} else if(parseInt(status) == 1) {
// remove the status
delete data.status;
var output = '<table class="table table-bordered"><thead><tr><th>Postcode</th><th>Area</th><th>State</th><th>Actions</th></tr></thead><tbody>';
$.each(data, function(k, v){
output += '<tr>';
output += '<td>'+ v.postcode +'</td>';
output += '<td>'+ v.area +'</td>';
output += '<td>'+ v.state +'</td>';
output += '<td class="text-center"><a id="set-location" href="#" lid="'+ v.id +'">Set</a></td>';
output += '</tr>';
});
output += '</tbody></table>';
$('#location-set-content').append(output);
}


});


});



return false;
});

表格创建没有问题 - 现在您可以看到最后一个字段 - <a id="set-location" href="#" lid="'+ v.id +'">Set</a>

这应该可以通过以下方式访问:

$('a#set-location').on('click', function(){
event.preventDefault();
var lid = $(this).attr('lid');
// Request
$.post('/api/postcode/set',
{
lid: lid
},
function(data){
if(data.status == 0) {
notification('location-set-content', data.response.message, 'danger', 0);
} else if(data.status == 1){
notification('location-set-content', data.response.message, 'success', 0);
go_to('/user/settings#location', 700);
}
console.log(data);
});

return false;
});

但这将不起作用,除非它在 each 的初始请求。所以基本上唯一可行的方法是如果 $('#id').on('click')功能在原来的submit里面.

当从第一个请求返回超过 1 个项目时,引起的问题是多个 ajax 请求,我将如何解决这个问题。

最佳答案

听起来您在页面加载时为 a#set-location 绑定(bind)了 click 事件。那时没有任何匹配的元素可以绑定(bind)。您想要做的是将处理程序附加到 DOM 上的文档就绪元素上。也许是这样的:

$('#location-set-content').on('click', 'a#set-location', function(){

甚至...

$(document).on('click', 'a#set-location', function(){

关于javascript - jQuery post 和 OnClick 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506982/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com