如何在HTML文件中进行函数调用在js文件中被识别 [英] How to make function call in HTML file be recognized in js file
本文介绍了如何在HTML文件中进行函数调用在js文件中被识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I have included code which works perfectly but when I move the javascript tags and code to a external .js file the function call in the html file is not recognized "function is not defined". I believe the problem is scope, of the function call in the html file... apparently its not global and therefore it is not recognized by the js file. When I moved the javascript code to an external file within the same folder as the html file I inserted <script src="myjsfile.js"></script> into the body section...I also tried inserting it into the head section, however it still didn't work. How can I make function calls (by button clicks) within my html file without having to include the javascript code in the html file? How would you fix this simple file?
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
<style>
#myDIV {
width: 200px;
height:100px;
background-color: #FC20FF;
color: #27FFF8;
}
</style>
</head>
<body>
<p>Click the button to set the backgroundColor property.</p>
<button onclick="myFunction()">Execute myFunction</button>
<div id="myDIV">
<h1>How are you?</h1>
</div>
<script>
function myFunction() {
document.getElementById("myDIV").style.backgroundColor = "#291CE8";
}
</script>
</body>
</html>
我尝试了什么:
移动javascript文件参考的位置以及在线发布的许多其他建议,但都没有奏效。大多数人都谈到本地和全局变量,我认为这是局部或全局函数问题。
What I have tried:
Moving the location of the javascript file reference and many of the other suggestions posted on line, but none of them worked. Most talked about local and global variables, this I believe is a local or global function problem.
推荐答案
使用单词myFunction作为函数的名称是问题。当我将名称更改为停止或去或其他单词时,它在单独的文件中与js一起正常工作。显然,myFunction这个词是一个受保护的词。
Using the word "myFunction" for the name of the function is a problem. When I changed the name to stop or go or some other word it worked fine with the js in a separate file. Apparently the word myFunction is a protected word.
这篇关于如何在HTML文件中进行函数调用在js文件中被识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文