在jQuery中如何在前一个函数完成后调用函数
任务是在JavaScript中顺序地执行一系列的函数。也就是说,在第一个函数执行完毕后,才执行第二个函数。
语法:
functionName();
方法:这个问题可以通过多种方式解决。
- 我们可以在函数一的末尾固定(硬编码)一个回调函数。这样做可以确保当函数一执行完毕时,回调函数总是被调用。然而,这种方法的一个问题是,我们不能在以后的运行时改变回调函数。我们将不得不删除这行代码或修改它。
- 另一种方法是将回调函数作为参数传递给函数一,并使函数一在其生命结束时调用这个新的回调函数。这种方法更加灵活,因为它允许我们在运行时改变回调函数,而无需实际修改任何一行代码。
让我们来详细了解一下它们中的每一个。
例子1:在这个例子中,我们将在函数一的末尾固定(硬编码)一个回调函数。
<!DOCTYPE html>
<html>
<head>
<title>
Call a function after
completing a function
</title>
</head>
<body>
<center>
<!-- gfg variable with no value initially -->
<h1>GeeksforGeeks</h1>
<b>A Computer Science Portal for Geeks</b>
<br>
<button>Click</button>
<p></p>
<script src=
"https://code.jquery.com/jquery-3.4.1.min.js">
</script>
<script type="text/javascript">
('button').click(function() {
console.log("Button clicked!");
// Task is to execute callbackFirst
// function first and then execute
// callbackSecond function.
callbackFirst();
});
function callbackFirst() {
console.log("First Function start");
for (var i = 1; i<10; i++) {
('p').append(i + " ");
}
console.log("First Function end");
// Execute callbackSecond() now as its
// the end of callbackFirst()
callbackSecond();
}
function callbackSecond() {
console.log("Second Function start");
('body').css({
'background-color': 'gray'
});
('h1').css({
'color': 'green'
});
console.log("Second Function end");
}
</script>
</center>
</body>
</html>
输出:
点击按钮后在控制台中:
Button clicked!
First Function start
First Function end
Second Function start
Second Function end
例2:在这个例子中,我们将把一个回调函数作为参数传递给函数一,这样它就可以在执行结束后调用这个新的回调函数。任务是先执行callbackFirst函数,然后执行callbackSecond函数。先把callbackSecond作为参数传给回调。
<!DOCTYPE html>
<html>
<head>
<title>Call a function after completeing a function</title>
</head>
<body>
<center>
<h1 style="color: green;">GeeksforGeeks</h1>
<b>A Computer Science Portal for Geeks</b><br>
<button style="color: green;">Click!</button>
<p></p>
<script src=
"https://code.jquery.com/jquery-3.4.1.min.js">
</script>
<script type="text/javascript">
('button').click(function() {
console.log("Button clicked!");
// Execute callbackSecond at the end
// of its execution
callbackFirst(callbackSecond);
});
function callbackFirst(callbackFn) {
console.log("First Function start");
for (var i = 1; i<10; i++) {
('p').append(i + " ");
}
console.log("First Function end");
/* Execute callbackFn() now as its
the end of callbackFirst() This
function was passed as a parameter */
callbackFn();
}
function callbackSecond() {
console.log("Second Function start");
('body').css({
'background-color': 'green'
});
('h1').css({
'color': 'black'
});
console.log("Second Function end");
}
</script>
</center>
</body>
</html>
输出:
点击按钮后在控制台中:
Button clicked!
First Function start
First Function end
Second Function start
Second Function end
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。