简体   繁体   English

Javascript函数可在HTML页面内运行,但不适用于外部.js文件

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

I am trying to place some Javascript code inside a .js file so that I can call it from multiple HTML pages. 我试图将一些Javascript代码放在.js文件中,以便可以从多个HTML页面调用它。 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. 问题是,如果将我的Javascript代码放在HTML页面内的脚本中,则我的Javascript代码可以正常工作,但是当放在外部.js文件中时,它根本不起作用。 I've looked at these questions quite a few times and still cannot find the error. 我已经看过这些问题很多次了,但仍然找不到错误。

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! 谢谢您的帮助!

You aren't returning anything from your IIFE. 您不会从IIFE返回任何东西。 contactsModule will then not contain anything, ie equal undefined . contactsModule将不包含任何内容,即等于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 您必须分配它们,或将它们定义为对象文字的一部分

Your code should be something like 您的代码应类似于

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

How about using 怎么样使用

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

});

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

Had the same problem. 有同样的问题。 Easy thing when you research on google. 当您在Google上进行研究时,这很容易。 Your Js code loads before the DOM loads. 您的Js代码会在DOM加载之前加载。 Which should be the other way around. 反之亦然。 So you have to use this 所以你必须用这个

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

Also JavaScript 还有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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的 script.js 文件不起作用,但 index.html 文件中的 JavaScript 代码起作用? - Why my script.js file doesn't work but the JavaScript code inside of the index.html file works? 加载html页面时,为什么我的外部javascript文件不起作用? - Why doesn't my external javascript file work when I load my html page? html页面中的javascript脚本块可以在标头中使用,但不能从外部文件中使用 - javascript script block in html page works in header but not from external file JavaScript - EventListener 在外部 js 文件中不起作用 - JavaScript - EventListener doesn't work in external js file 内联 js 有效,外部文件无效 - Inline js works, external file doesn't Javascript 在 html 中有效,但在 .js 文件中无效 - Javascript works in html but won't work in .js file 将Javascript代码从html移至外部js文件后,为什么为什么不起作用? - Why won't Javascript code work after moving it from html to an external js file? 从 html 文件中的外部 js 文件调用 Javascript 函数 - Calling a Javascript function from an external js file in the html file 从外部文件运行PaperScript / JavaScript不起作用 - Running PaperScript/JavaScript from an external file doesn't work 使用jQuery将JavaScript从外部HTML页面添加到JS文件 - Add JavaScript to js file from external html page using jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM