脚本在JSFiddle上运行正常,在其他地方失败

时间:2015-11-02 19:44:41

标签: javascript jquery html jquery-ui

我不知道如何使用jQuery库。相同的代码在JSFiddle中工作;这是以下链接:http://jsfiddle.net/NhhKd/

请有人告诉我为什么相同的代码在JSFiddle中有效,但在plunker或任何其他网站中没有。

$("#fruitList").sortable();

$("body").on('click', '#fruitList .delete', function () {
    $(this).closest(".fruit").remove();
});

$("#addFruit").click(function () {
    $('#fruitList').append("<li class='fruit'>New fruit<button class='delete'>Delete</button></li>");
});
#fruitList {
    margin: 0 auto;
    list-style:none;
    border: 1px solid #000000;
    width:150px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    padding:20px;
}
.fruit {
    cursor:pointer;
    border:1px solid #dddddd;
    background:#eeeeee;
    margin:5px;
    padding:5px;
}
button {
    background:#eeeeee;
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<button id='addFruit'>Add fruit</button>
<ul id="fruitList">
    <li class="fruit">Apple
        <button class="delete">Delete</button>
    </li>
    <li class="fruit">Banana
        <button class="delete">Delete</button>
    </li>
    <li class="fruit">Orange
        <button class="delete">Delete</button>
    </li>
</ul>

1 个答案:

答案 0 :(得分:1)

链接的JSFiddle包括jQuery UI。如果没有这个,你就会错过.sortable(),因为JavaScript console应该提醒你。

下面修改的片段包括jQuery UI和更现代的jQuery,就像JSFiddle一样。

$("#fruitList").sortable();

$("body").on('click', '#fruitList .delete', function () {
    $(this).closest(".fruit").remove();
});

$("#addFruit").click(function () {
    $('#fruitList').append("<li class='fruit'>New fruit<button class='delete'>Delete</button></li>");
});
#fruitList {
    margin: 0 auto;
    list-style:none;
    border: 1px solid #000000;
    width:150px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    padding:20px;
}
.fruit {
    cursor:pointer;
    border:1px solid #dddddd;
    background:#eeeeee;
    margin:5px;
    padding:5px;
}
button {
    background:#eeeeee;
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

<button id='addFruit'>Add fruit</button>
<ul id="fruitList">
    <li class="fruit">Apple
        <button class="delete">Delete</button>
    </li>
    <li class="fruit">Banana
        <button class="delete">Delete</button>
    </li>
    <li class="fruit">Orange
        <button class="delete">Delete</button>
    </li>
</ul>