javascript – 为什么这在jsfiddle中有效但在我的文档中没有用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 为什么这在jsfiddle中有效但在我的文档中没有用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2012字,纯文字阅读大概需要3分钟。
内容图文
我找到了一个很棒的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 onl oad模式中为你做这件事,即当你从左侧面板下拉选择onLoad时,所有js代码在DOM中出现所有资源后执行.
内容总结
以上是互联网集市为您收集整理的javascript – 为什么这在jsfiddle中有效但在我的文档中没有用全部内容,希望文章能够帮你解决javascript – 为什么这在jsfiddle中有效但在我的文档中没有用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。