Why does jQuery click-event fire when a page loads?

I have the following code .... When the page loads, myFunc () is called even if I do not find in my div. What for? The function declared as "inline" does not start ... 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>
+3
source share
7 answers

Due to your code:

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

is incorrect and should be:

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

Your code will call myFunc () first and then mimic the onclick event.

As can be seen from the documentation:

What you did is: (since myFunc returns null)

click ()

, . , . click : $( "" ) ();.

, :

click (fn) . . mousedown mouseup . :

+10

myFunc() $("#map").click(myFunc()) myFunc, $("#map").click. myFunc, :

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

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

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

+1

. :

<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>

, ( ).

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

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

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

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

myFunc() myFunc

0
source

This is expected from your code, because here:

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

The brackets () after the function will call it.

Try this instead:

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

    $(document).ready(function() {

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

    });
</script>
0
source

Source: https://habr.com/ru/post/1719952/


All Articles