javascript - How to change event execution order? - Stack Overflow

<!DOCTYPE html><html><head><meta charset="utf-8"><title>Close

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

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

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

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

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

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

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

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

but I want to show "temp2" first, and then show "temp1"

Is that possible? or the event execution order depends on the browser so I can't change it?

thanks for help!!

Share asked Nov 26, 2016 at 16:21 cyxcyx 1033 silver badges15 bronze badges 3
  • Why you do not write an unique function? – Marielitos Commented Nov 26, 2016 at 16:32
  • @Marielitos i think i too simplify my question, so I ask another question here, if you know the answer plz helping me thanks – cyx Commented Nov 26, 2016 at 18:24
  • I think U need change event model. Event capturing <-> Event bubbling. check this web: quirksmode/js/events_order.html – Adam G. Commented Jun 1, 2022 at 9:48
Add a ment  | 

2 Answers 2

Reset to default 2

Please review this one:

<!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>

There are a couple of ways in which you can guarantee the order here:

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

Another option would be:

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745043862a4607975.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信