如何在单击"Enter"按钮时添加标签(不是HTML),然后将其保存为字符串格式?



我正在尝试在文本框中添加标签。我搜索了相同的内容,但其中大多数都使用 github 或其他东西显示。我可以使用的一个是:

$('#textarea input').on('keyup', function(e) {
var key = e.which;
if (key == 188) {
$('<button/>').text($(this).val().slice(0, -1)).insertBefore($(this));
$(this).val('').focus();
};
});
$('#textarea').on('click', 'button', function(e) {
e.preventDefault();
$(this).remove();
return false;
})
#textarea {
border: 1px solid #eee;
}
#textarea input {
border: none;
background: none;
font-size: 1.2em;
padding: 6px;
}
#textarea input:focus {
outline: none;
}
#textarea button {
border: 1px solid #eee;
background: #f5f5f5;
margin: 4px;
font-size: 1.2em;
cursor: pointer;
}
#textarea button:after {
content: "d7";
color: red;
margin-left: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="textarea"><input type="text" /></div>

它确实得到了我想要的标签输入的东西,但我无法以字符串格式取回值。 请帮忙。

看看 .map 和 .get((

var tagsFromAngular = "testtag,abcd"
function tagify(input) {
$input = $(input), val = $.trim($input.val());
if (val !== "") {
$.each(val.split(","), function(_, tag) {
tag = $.trim(tag);
if (tag) $('<button/>').text(tag).insertBefore($input);
});
}
$input.val('').focus();
}
$(function() {
var $inp = $('#textarea input');
$inp.val(tagsFromAngular);
tagify($inp);
$inp.on('keyup', function(e) {
var key = e.which;
if (key == 13) {
tagify(this);
};
});
$('#textarea').on('click', 'button', function(e) {
e.preventDefault();
$(this).remove();
return false;
})
$("#show").on("click", function() {
console.log(
$("#textarea>button").map(function() {
return $(this).text()
}).get()
);
});
});
#textarea {
border: 1px solid #eee;
}
#textarea input {
border: none;
background: none;
font-size: 1.2em;
padding: 6px;
}
#textarea input:focus {
outline: none;
}
#textarea button {
border: 1px solid #eee;
background: #f5f5f5;
margin: 4px;
font-size: 1.2em;
cursor: pointer;
}
#textarea button:after {
content: "d7";
color: red;
margin-left: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="textarea"><input type="text" value="" /></div>
<button id="show" type="button">Show tags</button>

相关内容

最新更新