javascript - 如何包装单词以看起来像标签?
问题描述
我想听输入,当用javascript点击空格时,空格之前的单词将被包装成一个标签。
它应该类似于“公开提问”中的“标签”。到目前为止的代码:
html:
<label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off" oninput=""></textarea>
javascript:
document.getElementById('subtypes').addEventListener('input', function(evt){
wrapSubtypes(this.value);
});
function wrapSubtypes(value){
}
不知道往里面放什么wrapSubtypes(value)
。谢谢您的帮助。
解决方案
可能您想从函数中返回一个元素中的包装文本,例如:
return `<span class="tag">${value.trim().split(/\s/).pop()}</span>`
document.getElementById('subtypes').addEventListener('input', function(evt) {
if (evt.data === ' ') {
let tag = wrapSubtypes(this.value);
document.getElementById('tags').innerHTML += tag;
}
});
function wrapSubtypes(value) {
return `<span class="tag">${value.trim().split(/\s/).pop()}</span>`
}
#tags{ padding:10px; }
.tag {
border-radius: 25%;
color: #444;
background: #e5e5e5;
padding:5px;
margin-right:10px;
}
<div><label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off"></textarea>
</div>
<div id="tags"></div>
推荐阅读
- numpy - 需要运行两次单元格以使更改的代码显示输出
- r - 根据不同向量中的值重新编码向量中的变量
- r - 在 R 中聚合列总计
- python - openSMILE:在 python 中为 VAD 检测创建配置文件并运行信号处理
- python - elasticsearch.exceptions.ConnectionTimeout:由-ReadTimeoutError()引起的ConnectionTimeout
- node.js - 我们如何在不使用外部包和 tail -f 的情况下使用 node.js 继续查看大型日志文件并输出最后 10 行?
- graphql - Prisma 多对多关系查询
- c# - 让玩家以设定的长度冲向光标
- flutter - Firebase Googlemaps 错误不显示标记
- laravel-8 - 如何使用急切加载从雄辩的关系中仅返回json响应对象中的字符串列