简体   繁体   中英

How do external js work?? From what I've read this should work why doesn't it?

I'm having a very simple problem understanding the scope of variables with external javascript pages. From what I read if I call an external sheet all global functions and variables should be able to be accessed. I can't seem to get it to work. Knowing the right question to ask to search is the hard part and I could comb through the internet for days for a problem someone could probably explain easily and quickly. I have seen something simliar in this tutorial http://www.tizag.com/javascriptT/javascriptexternal.php , I searched quickly stack found this: What is the scope of variables in JavaScript? and even as I write this I'm looking for the answer.

Simply I have an external sheet in the same directory and the file name is trial.js. Then I have an index.html simply trying to use the global function from the external trial.js to the index page. This is possible? according to the tizag tutorial using a function in the button onclick attribute. Also many frameworks work on this principle too right? Although I know they are a bit more sophisticated using $(a)<~~~references?? or something. Thanks for anyone's help I'll continue to look but hopefully the internet can help!!

localhost/trial.js:

function trySomething(){
    alert("trying");
}

localhost/index.html:

<html>
<head>
<title>Objects222</title>
<script src="trial.js"></script>
</head>
<body>
    <script type="text/javascript">
        trySomething();
    </script>
    Hello
</body>
</html>

It was originally in resource but I wanted to make it even simplier. using firefox and chrome doesn't work for me??? Those who say it's working upon loading the page you get an alert that says "trying" ? Anyone any ideas why it might not be working locally. I cleared all my cache and tried renaming to force upload. Also used Chrome, Firefox, and IE still no alert on load @ localhost.

I'm not certain, but I don't think your supposed to have a / before "Resources". ex. "Resources/myscript" would work. Also, if "trial.js" is in the same directory as "index.html" then you don't need "Resources/".

我刚刚在Apache上进行了测试, 并假设您的外部JavaScript文件位于一个名为resource的文件夹中 ,它可以正常工作

This seems like it should be fine so I copied your code and tested it and it is working for me. The one change I made was to remove the first slash in the script src because my "resource" folder isn't in the site root. Is your js file definitely being loaded?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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