[英]Why does this work in jsfiddle but not in my document
我找到了一個很棒的jsfiddle,有人制作並希望在我的項目中使用它的一部分:
http://jsfiddle.net/manuel/29gtu/
它適用於jsfiddle,但不適用於我的HTML文檔。 這是我的文件中的內容:
<!DOCTYPE html>
<html>
<head>
<script src="scripts/jquery-1.7.2.js"></script>
<script>
$("button").click(function() {
var id = $("#id").val();
var text = "icon-"+id;
// update the result array
var result = JSON.parse(localStorage.getItem("result"));
if(result == null)
result = [];
result.push({id: id, icon: text});
// save the new result array
localStorage.setItem("result", JSON.stringify(result));
// append the new li
$("#bxs").append($("<li></li>").attr("id", "item-"+id).html(text));
});
// on init fill the ul
var result = JSON.parse(localStorage.getItem("result"));
if(result != null) {
for(var i=0;i<result.length;i++) {
var item = result[i];
$("#bxs").append($("<li></li>").attr("id", "item-"+item.id).html(item.icon));
}
}
</script>
</head>
<body>
<ul id="bxs" class="tabs">
</ul>
<input type="text" id="id" /><button>save</button>
</body>
</html>
代碼從小提琴中復制並粘貼。 我認為這與我沒有本地存儲插件有關。 為了讓jsfiddle工作,我需要一些我缺少的外部插件嗎?
你應該將整個代碼包裝在$(document).ready(function() {...});
所以。
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
var id = $("#id").val();
var text = "icon-" + id;
// update the result array
var result = JSON.parse(localStorage.getItem("result"));
if (result == null) result = [];
result.push({
id: id,
icon: text
});
// save the new result array
localStorage.setItem("result", JSON.stringify(result));
// append the new li
$("#bxs").append($("<li></li>").attr("id", "item-" + id).html(text));
});
// on init fill the ul
var result = JSON.parse(localStorage.getItem("result"));
if (result != null) {
for (var i = 0; i < result.length; i++) {
var item = result[i];
$("#bxs").append($("<li></li>").attr("id", "item-" + item.id).html(item.icon));
}
}
});
</script>
在jsfiddle
onLoad
模式中為你做這件事,即當你從左側面板下拉選擇onLoad
時,所有js代碼在所有資源出現在DOM中之后執行。
放入$(document).ready
就像這樣,也給出腳本標簽的類型
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
var id = $("#id").val();
var text = "icon-" + id;
// update the result array
var result = JSON.parse(localStorage.getItem("result"));
if (result == null) result = [];
result.push({
id: id,
icon: text
});
// save the new result array
localStorage.setItem("result", JSON.stringify(result));
// append the new li
$("#bxs").append($("<li></li>").attr("id", "item-" + id).html(text));
});
// on init fill the ul
var result = JSON.parse(localStorage.getItem("result"));
if (result != null) {
for (var i = 0; i < result.length; i++) {
var item = result[i];
$("#bxs").append($("<li></li>").attr("id", "item-" + item.id).html(item.icon));
}
}
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.