javascript函数在html中不起作用
我想从我的html页面中的java-script文件中调用一个函数。我的代码如下所示。javascript函数在html中不起作用
的index.html
<!DOCTYPE html>
<html><body>
<h2>Web1</h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
$(function() {
myFunction1(); // call function
});
</script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="socket.io.js"></script>
</body>
</html>
main.js
$(function() {
function myFunction1() {
alert("ff");
}
myFunction1()
是我的职责。它在$(function() {}
之内。但它不起作用。 它工作时,在main.js
function myFunction1() { // function declaration in global scope
alert("ff");
}
写道如何main.js
定义myFunction1()
内$(function() {}
?请帮帮我?在最后一行})()
(function() {
function myFunction1() {
alert("ff");
}
})()
注意的语法错误:
在我看来,它并不像是真的需要嵌套在匿名函数中。如果你删除它应该很好。
您需要jquery以后使用它的一部分。
基本上你需要切换函数声明和函数调用,因为在jquery的onload里面,你需要调用函数。
Puth全局范围外的函数声明。
function myFunction1() { // function declaration in global scope
alert("ff");
}
$(function() {
myFunction1(); // call function
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Web1</h2>
版本与本地函数声明。
$(function() {
function myFunction1() { // local function declaration
alert("ff");
}
myFunction1(); // call function
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Web1</h2>
<!DOCTYPE html>
<html>
<head>
<!--
You can uncomment this in your case
<script type="text/javascript" src="js/main.js"></script>
-->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<h2>Web1</h2>
<script>
$(document).ready(function(){
myFunction1();
});
function myFunction1() {
alert("ff");
}
</script>
</body>
</html>
这里是你的答案。 让我告知它对你有没有帮助。谢谢!在最后一行})()
我想在js文件中写入js函数。 – joe
是啊!你可以通过将脚本部分复制粘贴到单独的js文件中,然后取消注释脚本标记的注释代码来完成。 :) –
你缺少进口jQuery的和语法错误试试这个:
<!DOCTYPE html>
<html><body>
<h2>Web1</h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">
$(document).ready(function(){
myFunction1();
});
function myFunction1() {
alert("ff");
}
</script>
</body>
</html>
OR
<!DOCTYPE html>
<html><body>
<h2>Web1</h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">
$(function(){
myFunction1();
});
function myFunction1() {
alert("ff");
}
</script>
</body>
</html>
我必须清除它。但我的问题不解决。 – joe