jQuery回调到先前定义的函数 [英] JQuery callback to previously defined function
问题描述
我仍在学习JQuery(因此使用了一些JavaScript),但似乎无法找出如何在回调中使用先前定义的函数.
I'm still learning JQuery (and as a result a little JavaScript) but I can't seem to find out how to use a previously defined function in a callback.
说我有
<script>
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
});
</script>
我希望在另一个函数中使用它,例如:
And I wish to use this in another function e.g:
<script>
$(document).ready(function() {
$.ajax({
beforeSend: ajax_start(),
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
});
</script>
这是正确的吗? (我认为不是,因为它不是...)进行回调的正确方法是什么?
Would this be correct? (I assume not as it doesn't...) what is the proper way of doing a callback?
推荐答案
关闭.
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
$.ajax({
beforeSend: ajax_start, // <== remove the parens
url: "insert_part.php",
type:"POST",
data: "customer="+customer // <== as Skilldrick pointed out,
// remove the trailing comma as well
});
});
您需要这样做是因为
-
ajax_start()
通过执行名为ajax_start
的函数求出返回的值,但是 -
ajax_start
评估为函数本身.
ajax_start()
evaluates to the value returned by executing the function namedajax_start
, butajax_start
evaluates to the function itself.
我该如何在回调中包含第二个函数.类似的东西-事前发送:ajax_start,other_function(不完全是这样)?"
"how would I include a second function in the callback. Something like- beforesend: ajax_start,other_function (obv. not exactly like that)?"
有几种方法可以做到这一点.使用匿名函数将它们合并:
There are a couple ways to do it. Combine them using an anonymous function:
$.ajax({
// if you need the arguments passed to the callback
beforeSend: function (xhr, settings) {
ajax_start();
other_function();
},
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
或者只是声明一个执行所需功能的命名函数,然后使用它:
Or just declare a named function that does what you want, and then use it:
function combined_function(xhr, settings) {
ajax_start();
other_function();
}
$.ajax({
beforeSend: combined_function,
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
这篇关于jQuery回调到先前定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!