2016-11-26 132 views
1

如何更改事件執行順序?

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <meta charset="utf-8"> 
 
\t <title>Close window</title> 
 
</head> 
 
<body> 
 
\t <button id="abc" onclick="temp1()">button</button> 
 

 
<script type="text/javascript"> 
 
\t function temp1() { 
 
\t \t alert("temp1"); 
 
\t }; 
 

 
\t function temp2() { 
 
\t \t alert("temp2"); 
 
\t } 
 

 
\t document.getElementById("abc").addEventListener("click", temp2, false); 
 
</script> 
 
</body> 
 
</html>

,但我想顯示 「TEMP2」,然後再顯示的 「TEMP1」

這可能嗎?或者事件執行順序依賴於瀏覽器,所以我無法更改它?

感謝您的幫助!

+0

爲什麼你不寫一個獨特的功能? – Marielitos

+0

@Marielitos我想我也簡化了我的問題,所以我問另一個問題[這裏](http://stackoverflow.com/questions/40821567/how-to-set-the-event-to-be-triggered-first) ,如果你知道答案plz幫助我謝謝 – chenyuxian

回答

0

請仔細閱讀這一個:

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <title>Close window</title> 
 
</head> 
 

 
<body> 
 
    <!-- here is your first AddEventlistener--> 
 
    <button id="abc" onclick="temp1()">button</button> 
 

 
    <script type="text/javascript"> 
 
    function temp1() { 
 
     alert("temp1"); 
 
    }; 
 

 
    function temp2() { 
 
     alert("temp2"); 
 
    } 
 

 
    /*then here is your second AddEventlistener*/ 
 
    var d = document.getElementById("abc"); 
 
    d.addEventListener("click", temp2, false); 
 

 
    /*javascript will execute it in order 
 
     if you want to change the order. remove first EventListener then register new one after. something like this: 
 
    */ 
 
    //remove listener 
 
    d.onclick = null; 
 
    //register new 
 
    d.addEventListener('click', temp1); 
 
    </script> 
 
</body> 
 

 
</html>

+0

謝謝,我認爲你的答案是接近的,但我想我也簡化了我的問題,所以我問另一個問題[這裏](http:// stackoverflow.com/questions/40821567/how-to-set-the-event-to-be-triggered-first),如果你知道答案plz幫助我謝謝 – chenyuxian

+0

你不能指望老版本瀏覽器的訂單。 DOM級別2指定沒有訂單說明。但是,使用DOM級別3,您可以依靠訂單。見https://stackoverflow.com/questions/2706109/are-event-handlers-in-javascript-called-in-order –

0

有一對夫婦的方法,使你能保證這裏的順序:

document.getElementById("abc").addEvenListener("click", function() { 
    temp2(); 
    temp1(); 
}, false); 

另一種選擇是:

function temp2() { 
    alert(); 
    temp1(); // call temp1 at the end of temp2 
} 

document.getElementById("abc").addEventListener("click", temp2, false); 
+0

我想我也簡化了我的問題,所以我問另一個問題[這裏](http://stackoverflow.com/questions/40821567/how-to-set-the-event-如果你知道答案plz幫助我謝謝 – chenyuxian