javascript - 我在 textarea 中显示列表框的选定项目,但是当我修改 textarea 值时,它停止工作
问题描述
我有下一个代码来显示文本区域中列表框的选定选项:
$(".listBoxClass").change(function () {
var str = "";
$("#listBoxID option:selected").each(function () {
str = $(this).text() + " \n";
});
$("#textAreaID").append(str);
}).trigger("change");
它显然有效,但如果我删除一个单词,或在 textArea 中进行任何更改,代码将停止工作,所以如果我在 listBox 中选择其他项目,它不会出现在 textArea 中......我需要允许用户修改 textArea 值的选项,因此他也可以手动输入值
解决方案
您应该设置文本区域的值,而不是附加到它。而且您没有将它连接到字符串,而是在每次迭代中不断替换它。
$(".listBoxClass").change(function() {
var str = "";
$("#listBoxID option:selected").each(function() {
str += $(this).text() + " \n"; //concat it, do not replace, note the +=
});
$("#textAreaID").val(str); //replace tha value
}).trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="multiple" class="listBoxClass" id="listBoxID">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<textarea id="textAreaID"></textarea>
推荐阅读
- function - log_2(n+1)-log_3(2n+1)=O(1)吗?
- python - 未应用于生产的更改
- knockout.js - 淘汰赛:绑定到包含句点的 ID?
- terminal - zsh 使用命令标志作为目录?
- javascript - 切片数组并从中生成对象
- geopandas - Google Colab 中的 Geopandas
- scala - scala.collection.mutable.Map 抽象时如何扩展?
- localhost - kubectl port-forward 未绑定 IPv4 环回地址 127.0.0.1
- python - 如何在所有已安装的 python 包中搜索 vscode 中的类?
- javascript - 我想在我的网页(Wordpress)上实现一个视频文件,并使其在文件大小方面做出响应,以减少加载时间