当onclick事件处理机制启动时,为什么不调用第二个函数?

Why doesn't the second function gets called when onclick event handling mechanism is initiated?

本文关键字:调用 为什么不 第二个 函数 onclick 事件处理 机制 启动      更新时间:2023-09-26

考虑下面的代码片段,

<input type="button" value="Press Me!" id="my" onclick="return executeX(); executeY()">
<script>
    function executeX() {
        alert("in X");
        return true;
    }
    function executeY() {
        alert("in Y");
    }
</script>

尽管true第一个函数返回,为什么控件不在onclick中转到executeY() ?

使用&&来组合它们:

onclick="return executeX() && executeY();"

&&的短路保证了executeY()只有在executeX()返回真值时才会被调用。

因为在onclick处理程序中,您返回的是第一个函数的结果。它就像一个函数:一旦返回,就不会执行其他行。

这是因为您使用return开始内联javascript。因此,第一个函数一执行,它的结果就返回了。

要么删除返回值,要么在第一个函数的末尾调用第二个函数。

            function executeX(){
                alert("in X");
                executeY();
                return true;
            }   
            function executeY(){
                alert("in Y");
            }

在调用第二个函数(executeX())之前返回一个值(executeX())。

function example() {
    //Do Something
    return /*Return Something*/;
    //this Code will not be executed
}

可能的解决方案:

<input type="button" value="Press Me!" id="my" onclick="function(){ executeY(); return executeX(); }">