最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to execute javascript in different file? - Stack Overflow

programmeradmin3浏览0评论

I have multiple javascript functions in my html page. One of them, by far the biggest, is executed on a button click. If I moved that function into a separate .js file, what would be the syntax to have the onclick run that file?

I have multiple javascript functions in my html page. One of them, by far the biggest, is executed on a button click. If I moved that function into a separate .js file, what would be the syntax to have the onclick run that file?

Share Improve this question asked Apr 11, 2012 at 1:17 WilsonWilson 8,76820 gold badges72 silver badges102 bronze badges 1
  • Just make sure the script file is loaded before you try to use the functions defined within it. With jquery, for example, you'd wrap your calling code within a $(function () { /* here */ });. – Chris Farmer Commented Apr 11, 2012 at 1:22
Add a ment  | 

4 Answers 4

Reset to default 6

If the name of the function is still the same, then you don't have to do anything except include the script in your html somewhere before any code uses it, like so:

<script src="/yourscript.js" type="text/javascript"></script>

Your javascript functions can be in any number of files. You just need to add the reference to the .js file like this inside the tag:

<script type="text/javascript" src="path/to/scripts/filename.js"></script>

You don't have to change anything.

Just include your javascript file in your HEAD section, and the rest may remain the same. :-)

Your onclick doesn't run the file. It runs the function contained within that file. You wouldn't need to change the onclick syntax to make that happen.

发布评论

评论列表(0)

  1. 暂无评论