douzha5990 2014-11-07 22:33
浏览 86

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

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. 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. This last task was easily accomplished using http://www.jshint.com/, an online javascript parser. It's awesome.

I am trying to include a js file with javascript functions in my html file, and it isn't working. 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:

<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:

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:

1) The test.js file is not being properly loaded

or

2) The test.js file is being loaded, but it is throwing some syntax error.

Can anyone tell me why I can't execute the functions in my test.js script?

  • 写回答

1条回答 默认 最新

  • doushan3511 2014-11-07 22:50
    关注

    When I tried it in notepad++ and run in IE11, it works fine. however,

    The current state-of-the-art is to put scripts in the tag and use the async or defer attributes. This allows your scripts to be downloaded asap without blocking your browser.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题