【发布时间】:2018-02-09 19:21:03
【问题描述】:
我有一个 jQuery 事件处理函数,在单击两个按钮时触发 - 正面和负面。在任何一种情况下,我都会将不同的数据对象传递给处理程序(如下所示)。
我在这个事件处理程序中有一个 AJAX POST。但是我无法访问 AJAX POST 处理程序中的点击事件数据。
$('#Positive').on("click", {agree:true}, handlerFunc);
$('#Negative').on("click", {agree:false}, handlerFunc);
function handlerFunc(e){
e.preventDefault();
//e.data is valid here
if (e.data.agree === true){
//if condition is valid and it enters this block
startTimer();
}
$.post(url_, postData, function(data){
//console.log(e.data);
//e.data is undefined at this point
if (e.data.agree === false){
return true;
}
//do other stuff
});
}
为什么在 AJAX POST 中未定义 e.data?
我创建了一个新变量来存储 e.data.agree 值,它按预期工作。
$('#Positive').on("click", {agree:true}, handlerFunc);
$('#Negative').on("click", {agree:false}, handlerFunc);
function handlerFunc(e){
e.preventDefault();
//e.data is valid here
var agree_data = e.data.agree;
if (e.data.agree === true){
//if condition is valid and it enters this block
startTimer();
}
$.post(url_, postData, function(data){
//console.log(agree_data);
//agree_data is valid at this point
if (agree_data === false){
return true;
}
//do other stuff
});
}
为什么 e.data 在第一种情况下未定义 - 在 AJAX POST 中?它会被覆盖吗?
注意:我有两个不同的环境,它在测试环境中似乎工作正常,但在生产中给出了未定义的错误。
【问题讨论】:
-
@TheAlpha 你的代码和 OP 有什么不同?
-
@TheAlpha 是的,应该。我在我们的产品中使用 jQuery 2.2.3(尽管它也应该可以正常工作)。我有两个不同的环境,它似乎在测试环境中工作正常,但在生产中给出了未定义的错误。我整天都在敲我的头,因为它应该像你说的那样工作正常。
-
让我想知道
startTimer();代码是什么样子的 -
简单的答案是范围。 'e' 不再在回调中定义。
标签: javascript jquery ajax event-handling