JavaScript函数返回范围
函数触发一个数据库调用,该调用返回一些Json。然后使用此CID标记新添加的DOM元素 我需要检索/返回ajax成功块中存在的“cid”值,它将用于更新属性 错误 未定义cidJavaScript函数返回范围,javascript,jquery,Javascript,Jquery,函数触发一个数据库调用,该调用返回一些Json。然后使用此CID标记新添加的DOM元素 我需要检索/返回ajax成功块中存在的“cid”值,它将用于更新属性 错误 未定义cid //Save New Task $("body").on('click','.icon-facetime-video',function(event){ var new_entry = $(this).prev().val(); var thebid = $(this).parents('tbody').prev
//Save New Task
$("body").on('click','.icon-facetime-video',function(event){
var new_entry = $(this).prev().val();
var thebid = $(this).parents('tbody').prev().find('th').attr('id').split('_')[1];
$(this).parent().addClass('tk').html('<i class="icon-eye-open"></i> '+new_entry);
//CALL FUNCTION
var cid = update_entry('new_tk',new_entry,thebid); //value of cid from update_entry
$(this).parent().attr('id','cid_'+cid);
});
function update_entry(typeofupdate,new_entry,thebid){
switch(typeofupdate){
case 'new_tk': var action = 'new_tk';
break;
}
$.ajax({
type:'post',
url: 'posts_in.php',
dataType: "json",
data: {cid : thebid, action: action, content: new_entry},
success: function(data){
var action = data[0],cid= data[1];
console.dir(data);
}
});
return cid;
}
//保存新任务
$(“正文”)。在('单击','图标facetime video',函数(事件){
var new_entry=$(this.prev().val();
var thebid=$(this).parents('tbody').prev().find('th').attr('id').split('u')[1];
$(this.parent().addClass('tk').html(''+new_条目);
//调用函数
var cid=update_entry('new_tk',new_entry,thebid);//update_entry的cid值
$(this.parent().attr('id','cid_'+cid);
});
功能更新项目(更新类型、新项目、投标){
开关(更新类型){
案例'new_-tk':var action='new_-tk';
打破
}
$.ajax({
类型:'post',
url:'posts_in.php',
数据类型:“json”,
数据:{cid:thebid,action:action,content:new_entry},
成功:功能(数据){
var动作=数据[0],cid=数据[1];
console.dir(数据);
}
});
返回cid;
}
由于AJAX是异步完成的(因此AJAX中的a
),因此函数在AJAX调用完成之前返回。您应该将回调函数传递到update\u entry
,并在AJAX成功处理程序中运行它:
var self = this;
update_entry('new_tk', new_entry, thebid, function(cid) {
$(self).parent().attr('id', 'cid_' + cid);
});
function update_entry(typeofupdate, new_entry, thebid, callback) {
switch(typeofupdate){
case 'new_tk': var action = 'new_tk';
break;
}
$.ajax({
type:'post',
url: 'posts_in.php',
dataType: "json",
data: {cid : thebid, action: action, content: new_entry},
success: function(data){
var action = data[0], cid= data[1];
callback( cid );
console.dir(data);
}
});
}
Ajax调用不是同步的,所以您应该等待它返回该值。您可能还想在调用中编写一个
error:function()
,以防万一。可能重复的可能重复的请参见顺便说一句,您可能想为最近的
切换出父母
。非常感谢Joseph,这非常有帮助。:)