有没有办法让窗口事件先被触发

时间:2015-01-22 01:23:41

标签: javascript jquery

我需要首先触发窗口事件,点击#myDiv,有办法吗?

(function ($, w, d) {
    $(d).ready(function () {
      $(w).click(function() {
         alert('window has been clicked'); 
      });

      $('#myDiv').click(function () {
         alert('myDiv has been clicked'); 
      });
   });
})(jQuery, window, document);

查看http://jsfiddle.net/au1hpj5L/

1 个答案:

答案 0 :(得分:0)

您可以将匿名#myDiv函数包装在setTimout调用集中0秒,这将延迟其在事件循环中的执行。

http://jsfiddle.net/2y5h8fgz/

(function ($, w, d) {
    $(d).ready(function () {
        $(w).click(function() {
           alert('window has been clicked'); 
        });
        $('#myDiv').click(function(){
            setTimeout(function () {
           alert('myDiv has been clicked'); 
        }, 0);
        });
    });
})(jQuery, window, document);