Javascript函数在HTML页面内部工作,但不能从外部.js文件工作

时间:2021-05-03 02:21:43

I am trying to place some Javascript code inside a .js file so that I can call it from multiple HTML pages. The problem is, my Javascript code works fine if I place it in a script within the HTML page, but when placed in a external .js file, it simply does not work. I've looked at these questions quite a few times and still cannot find the error.

我试图在.js文件中放置一些Javascript代码,以便我可以从多个HTML页面调用它。问题是,如果我将它放在HTML页面的脚本中,我的Javascript代码可以正常工作,但是当放在外部.js文件中时,它根本不起作用。我已经看了好几次这些问题,但仍然找不到错误。

Here's the HTML page:

这是HTML页面:

<html>
<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="css/global.css" />
    <link rel="stylesheet" type="text/css" href="css/contacts.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src ="js/contactsModule.js"></script>
    <title>Hall of Heroes</title>
</head>
<body onload = "contactsModule.getContacts();">



    <!-- Global Header Starts Here -->
    <div class="header">
        <div class="cancel">
            <img src="img/cancel.png" /><!-- if screen is triggered from onboarding, then go back to onboarding screen instead of home -->
        </div>
        <h1>My Contacts</h1>
    </div>

    <div class="wrapper">
        <h3>A</h3> <!-- letter header goes here -->

        <!-- Begin Contact Unit -->
        <div class="feed">

        </div>
        <!-- End Contact Unit -->

    </div>

   </body>

   </html>

And here is the .js file:

这是.js文件:

var contactsModule = (function($){

        function getContacts()
        {
            dbContacts();
        }

        function displayContacts(contactArray){
            window.alert('displayContacts now running!');
            var jsonObject = $.parseJSON(contactArray);
            jsonObject.forEach(function (dat) {
                //Begin Contact Unit
                $('.feed')
                    .append('<div class="feed-img"><img src="' + dat.avatarUrl + '"/>\
                    </div><div class="feed-text"><p><span class="name_highlight">\
                    ' + dat.firstName + ' ' + dat.lastName + '</span></p></div>');
                //End Contact Unit
            });
        }
        function dbContacts() {
            var avatarUrl;
            var firstName;
            var lastName;

            $.ajax({
                type: "GET",
                url: "http://www.hallofheroesapp.com/php/contacts.php",
                data: {avatarUrl: avatarUrl, firstName: firstName, lastName: lastName},
                success: function (response) {
                    window.alert('AJAX ran successfully!');
                    displayContacts(response);
                },
                error: function(response){
                    alert("Error:" + response);
                }
            });
        }
 }(jQuery));

Thank you for your help!

谢谢您的帮助!

4 个解决方案

#1


2  

You aren't returning anything from your IIFE. contactsModule will then not contain anything, ie equal undefined. Also just defining functions doesn't make those functions part of some object, with the exception of globally defined functions. You have to assign them, or define them as part of an object literal

你没有从你的IIFE返回任何东西。 contactsModule将不包含任何内容,即等于undefined。除了全局定义的函数之外,仅定义函数不会使这些函数成为某个对象的一部分。您必须分配它们,或将它们定义为对象文字的一部分

Your code should be something like

你的代码应该是这样的

var contactsModule = (function($){
    return {
        getContacts: function() {
             /* code */
        },
        displayContacts: function(contactArray){
             /* code */
        }
        dbContacts function() {
             /* code */
        }
    };
 }(jQuery));

#2


0  

How about using

如何使用

$(document).ready(function(){
     ///// your code here...

});

#3


0  

... change ...

......改变......

<body onload = "contactsModule.getContacts();">

... to ...

... 至 ...

<body>

... and add event handler using jquery ...

...并使用jquery添加事件处理程序...

(function($){

        function getContacts()
        {
            dbContacts();
        }

        /* ... etc ... */

        // use jquery's onready handler
        $(getContacts);

 }(jQuery));

#4


0  

Had the same problem. Easy thing when you research on google. Your Js code loads before the DOM loads. Which should be the other way around. So you have to use this

有同样的问题。当你研究谷歌时很容易。您的Js代码在DOM加载之前加载。反过来应该是另一种方式。所以你必须使用它

$(document).ready(function(){
  //only jQuery is recommended, global JavaScript functions outside!
});

Also JavaScript

document.addEventListener("DOMContentLoaded", function(event) {
  //global function outside! 
});

Only this way you can be sure that your DOM is loaded before your jquery finds your elements.

只有这样,您才能确保在jquery找到元素之前加载了DOM。

#1


2  

You aren't returning anything from your IIFE. contactsModule will then not contain anything, ie equal undefined. Also just defining functions doesn't make those functions part of some object, with the exception of globally defined functions. You have to assign them, or define them as part of an object literal

你没有从你的IIFE返回任何东西。 contactsModule将不包含任何内容,即等于undefined。除了全局定义的函数之外,仅定义函数不会使这些函数成为某个对象的一部分。您必须分配它们,或将它们定义为对象文字的一部分

Your code should be something like

你的代码应该是这样的

var contactsModule = (function($){
    return {
        getContacts: function() {
             /* code */
        },
        displayContacts: function(contactArray){
             /* code */
        }
        dbContacts function() {
             /* code */
        }
    };
 }(jQuery));

#2


0  

How about using

如何使用

$(document).ready(function(){
     ///// your code here...

});

#3


0  

... change ...

......改变......

<body onload = "contactsModule.getContacts();">

... to ...

... 至 ...

<body>

... and add event handler using jquery ...

...并使用jquery添加事件处理程序...

(function($){

        function getContacts()
        {
            dbContacts();
        }

        /* ... etc ... */

        // use jquery's onready handler
        $(getContacts);

 }(jQuery));

#4


0  

Had the same problem. Easy thing when you research on google. Your Js code loads before the DOM loads. Which should be the other way around. So you have to use this

有同样的问题。当你研究谷歌时很容易。您的Js代码在DOM加载之前加载。反过来应该是另一种方式。所以你必须使用它

$(document).ready(function(){
  //only jQuery is recommended, global JavaScript functions outside!
});

Also JavaScript

document.addEventListener("DOMContentLoaded", function(event) {
  //global function outside! 
});

Only this way you can be sure that your DOM is loaded before your jquery finds your elements.

只有这样,您才能确保在jquery找到元素之前加载了DOM。