admin管理员组文章数量:1320915
I have this code:
var callbackAfterLoad = function(data, ecBlock) {
ecBlock.html(data);
ecBlock.slideDown();
}
function bindevents(userInput, ecBlock, callbackAfterLoad) {
userInput.keyup(function () {
delay(function () {
$.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock));
}, 500);
});
}
And this error:
Uncaught ReferenceError: data is not defined
But when I check out jQuery examples
$.post("test.php", function(data) {
alert("Data Loaded: " + data);
});
Why do I got this error ? Why do jQuery example is working and not mine ? (we cannot add parameters ?). Is the default $.post callback defined and his signature cannot be overriden ?
I have this code:
var callbackAfterLoad = function(data, ecBlock) {
ecBlock.html(data);
ecBlock.slideDown();
}
function bindevents(userInput, ecBlock, callbackAfterLoad) {
userInput.keyup(function () {
delay(function () {
$.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock));
}, 500);
});
}
And this error:
Uncaught ReferenceError: data is not defined
But when I check out jQuery examples
$.post("test.php", function(data) {
alert("Data Loaded: " + data);
});
Why do I got this error ? Why do jQuery example is working and not mine ? (we cannot add parameters ?). Is the default $.post callback defined and his signature cannot be overriden ?
Share Improve this question asked Jun 22, 2013 at 10:57 MaximeBernardMaximeBernard 1,1001 gold badge19 silver badges34 bronze badges2 Answers
Reset to default 6The third argument in $.post
should be a function, but when you do this:
$.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock))
The third argument is not the function, but the return value of the function. Like this:
fn = callbackAfterLoad // function reference
fn = callbackAfterLoad() // function execution and return value reference
And when executed in your example, data
is not available yet. The correct syntax would be:
$.post("/preview", {content:userInput.val()}, callbackAfterLoad)
If you need to pass custom arguments to your callback, you can create a new proxy function like this:
var callback = function(data) {
callbackAfterLoad.call(this, data, ecBlock);
};
$.post("/preview", {content:userInput.val()}, callback);
Try to use .post
method in little bit another way:
$.post("/preview", {content:userInput.val()}, function(data){ callbackAfterLoad(data, ecBlock)} );
Your example doesn't work because you're immediately calling to callbackAfterLoad
, before the .post
actually "happens" and returns data. In jQuery example the callback function is only registered as handler but not firing immediately.
本文标签:
版权声明:本文标题:javascript - jQuery: how to add parameter to a callback function without losing default parameter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741975400a2408090.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论