2017-05-07 120 views
0

我是JavaScript新手,我在YouTube上找到了教程。我完全按照教程设置来创建总和两个数字的函数,并创建html文件来执行,当我单击使用Web浏览器运行时。我感到非常困惑。请帮帮我。谢谢!简单的JavaScript与初学者

function add(a,b){ 
    return a+b; 

} 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="ISO-8859-1"> 
<title>Insert title here</title> 
<script type="text/javascript" src="myjs,js"></script> 
</head> 
<body> 
<script type="text/javascript">alert(add(100,200));</script> 
</body> 
</html> 
+2

有什么问题?另外'myjs,js'这里有一个逗号。 –

回答

3

看来你正在创建一个单一的文件。在这种情况下,add功能需要在里面script标签

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="ISO-8859-1"> 
 
    <title>Insert title here</title> 
 
    <script type="text/javascript" src="myjs.js"></script> 
 
</head> 
 

 
<body> 
 
    <script type="text/javascript"> 
 
    function add(a, b) { 
 
     return a + b; 
 
    } 
 
    alert(add(100, 200)); 
 
    </script> 
 
</body> 
 

 
</html>

另外,在这里

<script type="text/javascript" src="myjs,js"></script> 

一个错字逗号(,)需要用点来代替(.)

-1

请检查这个小提琴这是一个工作实例e为问题的问题是。在脚本

https://jsfiddle.net/rahulsingh09/Lww11j3t/

<script> function add(a,b){ 
    return a+b; 

}</script> 
<body> 
<script type="text/javascript">alert(add(100,200));</script> 
</body> 
+0

一个downvote的评论将不胜感激 –

0

好了,好运气学习,但你应该检查出像的Javascript只是好的部分主题一本书。另外学习jQuery并不是一个坏主意。我redid您的示例,并将其更改为接受用户输入并使用名称空间。当开始在全局命名空间中声明一个函数时,它很好,但是当你开始进入具有重叠方法的大型系统时,这是一个问题。

同时也学习如何使用chrome调试器,它在查找javascript代码问题时非常重要。如果你在调试器中打开,你会注意到在文件名myjs,JS没有加载的文件,它会记录大概一个404

/* Lets declare a self executing method, it auto-executes and keeps the document clean */ 
 
(function(){ 
 
    
 
    // Make a new namespace, i'm going to call it NS, but you could name it anything. This uses the OR logic to create if it doesn't exist. 
 
    window.NS = window.NS || {}; 
 
    
 
    // Declare your function in the name space 
 
    NS.add = function(a, b) { 
 
    return a+b; 
 
    }; 
 
    
 
}()); 
 

 
/* Wait till the document is ready, magic jQuery method */ 
 
$(function(){ 
 

 
    // No error prevention, this is just an example 
 

 
    // Wait till the user clicks Calculate 
 
    $('#Calculate').click(function(){ 
 
    var A = $('#A').val() - 0; // Get #A value, convert to number by subtwacting 0 
 
    var B = $('#B').val() - 0; // Get #B value, convert to number 
 
    // Call your method and set the value of #C 
 
    $('#C').val(NS.add(A, B)); 
 
    }); 
 

 
});
<!-- Use jQuery, its the best --> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div> 
 
    <!-- Declare a few fields, we like user input --> 
 
    <input type="text" id="A" value="1000"/> 
 
    <input type="text" id="B" value="337"/> 
 
    <!-- Use this field to hold input --> 
 
    <input type="text" readonly id="C"/> 
 
</div> 
 
<!-- One button to rule them all --> 
 
<button id="Calculate">Calculate</button>