如何在HTML中包含外部jQuery文件?

时间:2015-08-01 10:35:02

标签: javascript jquery html

我在JSFiddle中做了一个小例子。这是正确的,但现在我想将该示例的内容放在我的计算机中localhost的文件中。但是我遇到包含.js文件的问题。它没有加载。你能帮帮我吗?有什么问题?

这是我的JSFiddle示例:Click here

这是本地主机中的index.html文件:

<!DOCTYPE html>
<!--This is the first html page of the website-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="This is a simple example">
<meta name="keywords" content="multiple, add, substract"> 
<title>Tirana</title>
<link rel="stylesheet" type="text/css"  href="style2.css">
<link rel="icon" href="images/logo.png" type="image/png" sizes="40x35">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="code.js"></script>
</head>
<body>

<div class="container">
<textarea id="input" name="Input1" cols="40" rows="5" placeholder="enter your input here">
number a =5
number b =7
sum = a+b 
</textarea>
<input type="button" value="test" />
<textarea id="output" name="Output1" cols="40" rows="5" placeholder="output" readonly></textarea>
   </div>

</body>
</html>

我使用它来包含.js文件:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <script type="text/javascript" src="codejs.js"></script>

这是我的codejs.js文件:

$('input[type=button]').click(function () {
    var result= "";
    var lines = $('#input').val().split('\n');

    for (var i = 0; i < lines.length; i++) {
            result += lines[i];
            result += "\n";
    }

    $("#output").html(result);

});
你能帮助我吗?提前致谢

2 个答案:

答案 0 :(得分:4)

您正在寻找的是管理js文件的依赖关系。有许多可能的选项,比如使用require库。

关于您的代码,解决问题的最简单方法是将代码移到ready块中。

$(document).ready(function(){
     // move your code here
});

答案 1 :(得分:1)

你可以做Nikhil正在做的事情,或者你可以做到这一点。

你错过了

$(function(){  // DOM IS NOW READY

    /* YOUR CODE HERE */

});

jQuery docs .ready()

为您的代码尝试这样。

$(function(){
$('input[type=button]').click(function () {
    var result= "";
    var lines = $('#input').val().split('\n');

    for (var i = 0; i < lines.length; i++) {
            result += lines[i];
            result += "\n";
    }

    $("#output").html(result);

});
});