1.如何从此输入中获取值
<input type="text"></input>
将其附加到带有本地存储的 DOM,这样即使刷新页面也会保存它。
- 我想用删除图标选项附加它,所以当我单击它时,它将 localStorage.removeItem(); 从 DOM 不刷新页面。
刷新:
示例存储本地,抱歉没有时间扩展版本(稍后会做):
var dogname = "Skippy";
localStorage.setItem("dog", dogname);
var dogLocal = localStorage.getItem("dog");
$("#dog").html(dogLocal);
http://jsfiddle.net/Andelhofs/59dsL7s8/1/
我怀疑您正在尝试执行类似于SO中的标记功能的操作,即使用关键术语标记问题,添加它们,然后选择删除它们。这是对的吗?如果是这样,请看我在 http://jsfiddle.net/u7tkoo6n/写的快速JS小提琴。
由于我必须将上面的链接与代码一起提供,因此它是:
.HTML:
<form>
<input type="text" id="name" name="name" />
<input type="submit" value="Add" id="addName" />
</form>
<div class="names-panel"></div>
j查询:
$(document).ready(function() {
$("#addName").click(function(e) { // On click of the button
var val = $("#name").val(); // Get the current value
if(val) {
$("#name").val(""); // Blank out the text input
var names = localStorage.getItem("names");
if(names) {
names += "," + val;
} else {
names = val;
}
localStorage.setItem("names", names);
updateNames();
}
e.preventDefault();
return false;
});
updateNames();
});
function updateNames() {
var names = localStorage.getItem("names");
if(names) {
names = names.split(",");
$(".names-panel").html("");
for(var i = 0; i < names.length; i++) {
var item = $("<span class="item">" + names[i] + "<span class="ui-icon ui-icon-close" data-name="" + names[i] + ""></span></span>");
item.find(".ui-icon-close").click(function() {
var currentName = $(this).data("name");
var names = localStorage.getItem("names");
names = names.split(",");
var position = names.indexOf(currentName);
if(position > -1) names.splice(position, 1);
names = names.join();
localStorage.setItem("names", names);
updateNames();
});
$(".names-panel").append(item);
}
}
}
CSS(纯粹是为了外观和感觉):
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input[type=text] {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
border: 1px solid #ccc;
}
.item {
display: inline-block;
width: auto;
border: 1px solid #ccc;
background-color: #eee;
padding: 3px 40px 3px 8px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
margin: 5px 5px 5px 0;
position: relative;
}
.item .ui-icon {
position: absolute;
right: 0;
top: 3px;
}
.item .ui-icon.ui-icon-close {
cursor: pointer;
}
它可能会写得更好(我倾向于将其编写为 jQuery UI 插件,但认为这可能需要更长的时间),但它仍然可以完成工作。