-
Notifications
You must be signed in to change notification settings - Fork 0
/
convey
84 lines (76 loc) · 2.32 KB
/
convey
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage</title>
<script src="./js/jquery-1.11.1.js"></script>
<script>
var json_obj = {
"favorite":[]
};
$(document).ready(function(){
$('.test').click(function(){
setItem(this); // 存進localStorage
})
});
function setItem(element){
var id = $(element).attr("id"); // 取button的id
var url = $(element).html(); // 取button中的值
if (typeof(Storage) != "undefined") {
if(!(hasExisted(id))){ // 如果json裡不存在相同id/name
var arr = json_obj.favorite; // 抓出裡面的favorite
var newItem = {"name":id, "url":url};
arr.push(newItem); // push進去
localStorage.setItem("favorite", JSON.stringify(json_obj));
}
else{ // 已經存在,則秀出提示
alert("此網頁已經在我的最愛了!");
}
}
else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
function hasExisted(id){
getItem();
for(var i = 0; i < json_obj.favorite.length; i++){
if (id == json_obj.favorite[i].name)
return true;
}
return false;
}
function getItem(){
if (typeof(Storage) != "undefined") {
var data = localStorage.getItem("favorite");
if (data != null){
json_obj = JSON.parse(data);
}
}
else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
</script>
</head>
<style>
body {
font-family: Arial, "文泉驛正黑", "WenQuanYi Zen Hei", "微軟正黑體", "Microsoft JhengHei", "標楷體", sans-serif;
}
.test {
width: 15%;
height: 80px;
}
</style>
<body>
<div style="text-align: center; margin-top: 100px">
<h1>點擊button新增至我的最愛</h1>
<button class="test" id="first">http://ppt.cc/L!f7</button>
<button class="test" id="second">http://ppt.cc/8Hjm</button>
<button class="test" id="third">http://ppt.cc/eT7A</button>
<button class="test" id="fourth">http://ppt.cc/YAJG</button>
<button class="test" id="fifth">http://ppt.cc/itGl</button>
<br><br>
<a href="localstorage.html"><button>前往我的最愛</button></a>
</div>
</body>
</html>