简体   繁体   中英

Jquery Function not being called?

Please why on earth isn't the function being call I have spent close to an hour on this:

This is the jquery:

function toggleDivs() {
    var $inner = $("#inner");

    // See which <divs> should be animated in/out.
    if ($inner.position().left == 0) {
        $inner.animate({
            left: "-400px"
        });
    }
    else {
        $inner.animate({
            left: "0px"
        });
    }
}

$("button").bind("click", function() {
        alert("Hello");
    toggleDivs();
});

This is the head section in my html

<head>
<script type="text/javascript" src="PageScript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Lato:100,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="PageStyle.css">
</head>

Your head is incorrect. Kindly change the follow into this order:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="PageScript.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Lato:100,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="PageStyle.css">
</head>

Explination:

Your PageScript.js will load first before the jquery.min.js because of this, all your jquery functions from your PageScript.js will cause an error.

1)your code is working fine.

2) use ready function to use bind function

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="PageScript.js"></script>
      <script>

    function toggleDivs() {
    alert('hi');
    } 
    $( document ).ready(function() {
    $("button").bind("click", function() {
            alert("Hello");
        toggleDivs();
    });
     });  
        </script>

Try with

$("button").on("click", function() {
        alert("Hello");
    toggleDivs();
});

If its dynamic button use event delegation

$(document).on("click",'button',function() {
        alert("Hello");
    toggleDivs();
});

Scripts order wrong.Jquery must first and then others

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="PageScript.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Lato:100,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="PageStyle.css">
</head>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM