gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:36:08 26 4
gpt4 key购买 nike

我有以下代码......当页面加载时,即使我没有点击我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com