簡體   English   中英

Javascript函數可在HTML頁面內運行,但不適用於外部.js文件

[英]Javascript Function works inside HTML page but doesn't work from external .js file

我試圖將一些Javascript代碼放在.js文件中,以便可以從多個HTML頁面調用它。 問題是,如果將我的Javascript代碼放在HTML頁面內的腳本中,則我的Javascript代碼可以正常工作,但是當放在外部.js文件中時,它根本不起作用。 我已經看過這些問題很多次了,但仍然找不到錯誤。

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

這是.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));

謝謝您的幫助!

您不會從IIFE返回任何東西。 contactsModule將不包含任何內容,即等於undefined 同樣,僅定義函數並不能使這些函數成為某些對象的一部分,但全局定義的函數除外。 您必須分配它們,或將它們定義為對象文字的一部分

您的代碼應類似於

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

怎么樣使用

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

});

...改變...

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

... 至 ...

<body>

...並使用jQuery添加事件處理程序...

(function($){

        function getContacts()
        {
            dbContacts();
        }

        /* ... etc ... */

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

 }(jQuery));

有同樣的問題。 當您在Google上進行研究時,這很容易。 您的Js代碼會在DOM加載之前加載。 反之亦然。 所以你必須用這個

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

還有JavaScript

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

只有這樣,您才能確定在jQuery找到元素之前已加載DOM。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM