簡體   English   中英

如何在jQuery的函數內調用函數

[英]how to call function within the function in jquery

如果我單擊按鈕,我想在函數hello。中調用?可以調用嗎?

 <!DOCTYPE html>
 <html>
 <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"    type="text/javascript"></script>

  <script>
  function hai(){
      alert("hai fun");
   function hello(){
     alert("hello function");
    }
 }
 </script>
 </head>
 <body>
 <button onclick="hello()">click here</button>
 </body>
 </html>

除非已將另一個函數中定義的函數附加到該函數外部可訪問的對象,否則它們將無法在該函數外部訪問。

function hai(){
      alert("hai fun");
 }

function hello(){
     alert("hello function");
     hai();
    }

<button onclick="hello()">click here</button>

DEMO

將其設置為變量:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"    type="text/javascript"></script>
        <script>
            function hai(){
                alert("hai fun");
                whatYouAreLookingFor = function hello()
                {
                    alert("hello function");
                }
                whatYouAreLookingFor();

            }
        </script>
    </head>
    <body>
        <button onclick="hai()">click here</button>
    </body>
</html>

這是調用內部函數的一種方法,但是它需要修改外部函數的代碼並傳入變量以獲取內部函數。

HTML

<body>
    <button onclick="funcVariable()">click here</button>
</body>

使用Javascript

var funcVariable;

function hai(funcVar) {
    funcVar = function hello() {
        alert("hello function");
    };

    return funcVar
}

funcVariable = hai(funcVariable);

現在按下按鈕將顯示警報。

參見JSFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM