jquery - 为什么页面加载时会触发 jQuery 点击事件?

标签 jquery events click

我有以下代码...... 当页面加载时,即使我没有点击我的 div,myFunc() 也会被调用。为什么? 声明为“inline”的函数没有被触发...hmmmm........

<div id="map" style="background: green; height: 100px"></div>

<script type="text/javascript">
    function myFunc() {
        alert("allways triggered when page loads...");
    };

    $(document).ready(function() {

    $("#map").click(myFunc());
    $("#map").click(function() { alert("not triggered") });

    });
</script>

最佳答案

因为你的代码:

 $("#map").click(myFunc());

这是错误的,并且必须是:

$("#map").click(myFunc);

您的代码将首先调用 myFunc(),然后模拟 onclick 事件。

如文档中所示:

你所做的是这样的:(因为 myFunc 返回 null)

click( )

Triggers the click event of each matched element. Causes all of the functions that have been bound to that click event to be executed. To trigger the click event on all of the paragraphs on the page: $("p").click();

你想要的是这样的:

click( fn ) Binds a function to the click event of each matched element. The click event fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:

关于jquery - 为什么页面加载时会触发 jQuery 点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1558584/

相关文章:

javascript - JQuery 在创建 DOM 元素后做一些事情 - DOMNodeInserted 不工作

javascript - 为什么我的文本框的 onchange 事件会在模糊时触发 - 不是每个键入的字符都会触发?

javascript - 仅启用 mouseup 事件 Jquery 中的 Click 事件

Ubuntu 9.10上的Eclipse Galileo单击问题

php - Jquery Ajax从php mysql获取数据而不刷新页面 - 语法错误

javascript - 为什么 ("click"、 "button"、...) 上的 jQuery 在单击按钮之前运行?

javascript - 将一个 div 的元素发送到另一个 div

powershell - 将参数传递给Register-EngineEvent操作脚本 block

javascript - jQuery 如何使点击处理程序始终引用父级?

javascript - 有什么方法可以获取文本内容的Element?