简体   繁体   English

如何在html / php中包含外部js并调用函数

[英]How to include external js in html/php and call a function

SOLUTION FOUND: Firstly, the code below DOES in fact work. 找到的解决方案:首先,下面的代码确实有效。 Sorry about that. 对于那个很抱歉。 Moreover, my more complex code (not shown) was NOT WORKING BECAUSE MY .js SCRIPT HAD SYNTAX ERRORS IN IT. 而且,我更复杂的代码(未显示)无法正常工作,因为我的.js脚本中有语法错误。 Note, these syntax errors had nothing to do with the functions I was attempting to invoke, which were the top two functions in the script. 注意,这些语法错误与我尝试调用的函数无关,它们是脚本中最重要的两个函数。 This means you must make sure your entire .js is flawless before attempting to load any of its functions. 这意味着您在尝试加载其任何功能之前,必须确保整个.js均无缺陷。 This last task was easily accomplished using http://www.jshint.com/ , an online javascript parser. 使用在线JavaScript解析器http://www.jshint.com/可以轻松完成最后一项任务。 It's awesome. 这很棒。

I am trying to include a js file with javascript functions in my html file, and it isn't working. 我试图在我的html文件中包含一个带有javascript函数的js文件,但是它不起作用。 I won't claim to have tried everything, but I've tried most things. 我不会声称尝试了所有事情,但是我尝试了大多数事情。 For simplicity, I have placed test.html and test.js IN THE SAME FOLDER. 为简单起见,我将test.html和test.js放在同一文件夹中。

test.html: test.html:

<html>
    <script type="text/javascript" src="test.js"></script>
    <script type="text/javascript">
        alert('1!'); // for debugging
        testAlert(); // supposed to pop-up alert BUT IS ERRORING OUT HERE!
        alert('2'); // for debugging
        alert(testStr());
        alert('3'); // for debugging
    </script>

    <body>
        The body.
    </body>
</html>

test.js: test.js:

function testStr()
{
   return "hello";
}

function testAlert()
{
   alert('initYEAH!');
}

When I load test.html in my browser, the first debug alert pops up, but the second debug alert never does, telling me that one of two things is happening: 当我在浏览器中加载test.html时,会弹出第一个调试警报,但是第二个调试警报却从不弹出,告诉我正在发生以下两种情况之一:

1) The test.js file is not being properly loaded 1)test.js文件未正确加载

or 要么

2) The test.js file is being loaded, but it is throwing some syntax error. 2)正在加载test.js文件,但它抛出一些语法错误。

Can anyone tell me why I can't execute the functions in my test.js script? 谁能告诉我为什么我无法在test.js脚本中执行功能?

When I tried it in notepad++ and run in IE11, it works fine. 当我在notepad ++中尝试并在IE11中运行时,它工作正常。 however, 然而,

The current state-of-the-art is to put scripts in the tag and use the async or defer attributes. 当前的最新技术是将脚本放入标签中,并使用async或defer属性。 This allows your scripts to be downloaded asap without blocking your browser. 这样一来,您的脚本就可以尽快下载,而不会阻止浏览器。

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

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