简体   繁体   中英

jQuery code doesn't work when put within head tag

I have a jQuery code that works when I insert it inside a script tag within the body. But it doesn't work when I insert it in the head tag or include it as a js file.

Judging from your description you most probably forgot to put your script into a $(document).ready function:

$(function() {
    // put your code here
});

Then you can place this wherever you want on the page ( head , body , external script, ...).

Any script code put inside a head is not supposed to execute automatically. Unless called by a event listener. So if you have put your code in the head section its just a piece of functionality waiting to be executed on a call. This code can be called as mentioned on a document.ready( ) event handler or any other event call from the user.

try these format

<html>
<head>
<script>
 $(document).ready(function()    {
        $('#arrow img').click(function()    {
            transferEmp('test');
        });
 });
</script>
<body>
<!-- other tags -->
<script>
 $(document).ready(function()    {
        $('#arrow img').click(function()    {
            transferEmp('test');
        });
 });
</script>
<script src="test.js" type="text/javascript"></script>
</body>
</html>

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