为什么当页面加载时jQuery点击事件触发? [英] Why is jQuery click-event triggered when page loaded?

查看:330
本文介绍了为什么当页面加载时jQuery点击事件触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  ; div id =mapstyle =background:green; height:100px>< / div> 

< script type =text / javascript>
function myFunc(){
alert(加载...时触发allways);
};

$(document).ready(function(){

$(#map)。click(myFunc());
$(地图)。click(function(){alert(not triggered)});

});
< / script>由于您的代码: $ b



解决方案
$ b

  $(#map)。click(myFunc()); 

错误,必须为:

  $(#map)。click(myFunc); 

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



如文档中所示:



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


click()



触发每个匹配元素的点击事件。
使得绑定到该单击事件的所有函数都被执行。
触发页面上所有段落的点击事件:
$(p)。click();


你想要的是:


点击(fn)
将函数绑定到click事件每个匹配元素。
当点击指针设备按钮覆盖元素时,点击事件触发。点击被定义为在同一屏幕位置上的mousedown和mouseup。这些事件的顺序是:



I have the following code.... When the page is loaded myFunc() is called even if I dont click in my div. Why? The function declared "inline" is not triggered...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>

解决方案

Because of your code:

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

is wrong and has to be:

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

Your code would call myFunc() first and than simulate a onclick event.

As seen in the documentation:

What you did is this: (as myFunc returns 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();

What you want is this:

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点击事件触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆