听到我在Textbox1中键入的内容是通过将空格作为分隔符转换为textbox2中的标签,以便将文本从一个文本框反映到另一个文本框我使用了keydown函数,每个东西都工作正常但是(参见下面的代码),假设我在textbox1中键入'home',然后在textbox2中只显示'hom'(缺少最后一个字符)。我怎么能克服这个问题......?
如果我使用keyup然后它解决了上述问题,但是当我删除生成的标签(键入任何类似'home on fire'并删除'on')然后观察textbox1它显示'home fire'但textbox2将是相同的(并反映到DB相同)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
.tag span {
color: red;
margin-left: 10px;
display:inline-box;
cursor: pointer;
}
body {
font-family: Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif;
}
.tag {
color: #3E6D8E;
background-color: #E0EAF1;
border-bottom: 1px solid #b3cee1;
border-right: 1px solid #b3cee1;
padding: 3px 4px 3px 4px;
margin: 2px 2px 2px 0;
text-decoration: none;
font-size: 90%;
line-height: 2.4;
white-space: nowrap;
}
.tag:hover {
background-color: #c4dae9;
border-bottom: 1px solid #c4dae9;
border-right: 1px solid #c4dae9;
text-decoration: none;
}
</style>
<script src="jquery.min.js"></script>
<script>
function delTag(tgt) {
var a = $(tgt).parent().text();
// remove the "X", trim
a = a.substring(0, a.length - 1).replace(/^\s+|\s+$/, "");
// hackky, probably want to replace this with a regular expression matching spaces (\s) or start (^) or end ($)
var newVal = (" " + $("#textBox").val() + " ")
// remove tag
newVal = newVal.replace(a + " ", "");
// update
$("#textBox").val(newVal).trigger("keydown");
}
$(document).ready(function () {
var tags = [];
var arrayValue;
$("#textBox").keydown(function (e) {
$(".target").html(""); //clear
// trimmed
var text = this.value.replace(/^\s+|\s+$/g,"");
if (text === "") {
return;
}
tags = text.split(/\s+/);
console.log(tags);
$.each(tags, function (ind, tag) {
var span = "<span onclick='delTag(this)'>X</span>";
$(".target").append($("<a href='#' class='tag'>").text(tag).append(span));
});
});
$("button").click(function () {
tags.join("");
alert(tags);
});
});
</script>
</head>
<body>
<div>
TextBox 1 :
<input type="textbox" id="textBox"></input>TextBox 2 :
<div class="target" contenteditable="true"></div>
<button>Save to DB</button>
</div>
</body>
</html>
根据我的说法
keydown意味着:
Fires when the user depresses a key. It repeats while the user keeps the key depressed.
按键意味着:
Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.
keyup表示:
Fires when the user releases a key, after the default action of that key has been performed.
听到的问题是什么?