您在这里混淆了担忧。 alert() 是一个 UI 操作,它不会触发代码中的任何内容。它只是在 UI 上做一些事情。如果您希望您的函数在代码中触发其他内容,则需要调用其他内容:
function stepLeft() {
if (danger == 1) {
alert("stop")
someOtherFunction();
} else {
alert("start")
yetAnotherFunction();
}
}
或者,如果功能可以更改,您可以向stepLeft 提供一个函数:
function stepLeft(stopFunction, startFunction) {
if (danger == 1) {
alert("stop")
stopFunction();
} else {
alert("start")
startFunction();
}
}
然后调用它:
stepLeft(someOtherFunction, yetAnotherFunction);
或者您可能让stepLeft 返回一个值,其他函数可以使用该值:
function stepLeft() {
if (danger == 1) {
alert("stop")
return "stop";
} else {
alert("start")
return "start";
}
}
然后调用它:
var actionPerformed = stepLeft();
someOtherFunction(actionPerformed);
这实际上是一个将 UI 操作与逻辑分离的好机会:
function stepLeft() {
if (danger == 1) {
return "stop";
} else {
return "start";
}
}
和:
var actionPerformed = stepLeft();
alert(actionPerformed);
someOtherFunction(actionPerformed);
关键是,有很多方法可以构建代码,以便一个函数的结果可以被另一个函数使用。