Why my jQuery code can run on jsfiddle but not on Dreamweaver or browser?

↘锁芯ラ 提交于 2019-12-11 10:36:58

问题


My jQuery code can run on jsfiddle but not on Dreamweaver nor browser? Here is the link to my code on JSfiddle, and below is my codes. please help me check if there is something missing? http://jsfiddle.net/sbmp3apz/6/

HTML:

<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">   </script>
<script type="text/javascript" src="script2.js"></script>
<meta charset="utf-8">
<title>lab1</title>
</head>

<body>
pick your fruit:
<input type="text" id="newfruit">
<br>

<h1> Fruit Shelf:</h1>

<div id="div1">
    <ol id="fruits"></ol>
</div>

<h1>Basket:</h1

<ol id="basket"></ol>
<button>add fruit</button>
</body>
</html>

JS:

    var fruitslist = ["pear", "apple", "peach", "grapes", "strawberry", "melon"];
$( document ).ready(function() {

$.each(fruitslist, function(){
    $("<li>").text(this).appendTo("#fruits");
});


$('button').click(function () {
    var ipt = $("#newfruit").val();
    if(fruitslist.indexOf(ipt) > -1){
        $("<li>").text(ipt).appendTo("#basket");
        fruitslist = $.grep(fruitslist, function(value){
            return value != ipt;
        });
        $("#fruits > li").filter(function(){
            return $(this).text() === ipt;
        }).remove();
    }
});
});

回答1:


There are three things need to be pay attention:

  1. Must load jQuery on your page. Like this:
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

  2. the jQuery lib position must load before your script.

  3. your code must be wrapped used $(function (){}), or your code load after the DOM loaded.




回答2:


You do not have the JQuery framework (dependency) linked in the head before your own script:

http://puu.sh/bDukO.PNG

add this line to your html code directly underneath the head tag and before your own script:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

Note You dont need the 'type' attribute in script tags in HTML5 anymore




回答3:


You have an open tag in your example code.

Your example code (just line 21):

<h1>Basket:</h1

Should be

<h1>Basket:</h1>

It appears closed in your JSFiddle example. Hope that helps.



来源:https://stackoverflow.com/questions/25902930/why-my-jquery-code-can-run-on-jsfiddle-but-not-on-dreamweaver-or-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!