在IE8中,jQuery mousedown事件没有为窗口触发

时间:2011-12-07 10:38:28

标签: javascript jquery javascript-events internet-explorer-8

我在使用IE8中的jQuery挂钩窗口的mousedown事件时遇到了问题。我没有得到任何错误,但事件似乎没有被解雇。它在IE9和我尝试过的所有其他浏览器中都有效。这是我的代码:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function test(e) {
            alert('test');
        }

        $(document).ready(function () {
            $(window).mousedown(test);
        });     
    </script>   
</head>
<body>   
</body>
</html>

2 个答案:

答案 0 :(得分:5)

使用document代替window

$(document).ready(function() {
    $(document).mousedown(function() {
        alert('test');
    });
});

答案 1 :(得分:1)

问题是您使用的是全局window.event对象,而不是jQuery的事件对象。 window.event只能在某些浏览器中使用,而且它不是W3C标准。

jQuery规范化事件对象,使其在所有浏览器中都相同。事件处理程序将jQuery事件对象作为参数传递。你应该使用它。

 $(".class_name").mousedown(function (e) {

  switch (e.which) {
    case 1: //leftclick
        //...
        break;
    case 3: //rightclick
        //...
        break;
  }
});