javascript - 多个 div 选择 onclick
问题描述
我有多个带有 id 的 div,onclick 我将 div 的 id 存储在一个输入值中,但它只需要一个 id,我想进行多项选择并将所有选定的 div id 存储在同一个输入中,这是我的代码:
function storeId (el) {
$('input').val(el.id);
}
div{
background-color:red;
height: 50px;
width: 50px;
margin-bottom: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1" onclick="storeId(this);">
</div>
<div id="div-2" onclick="storeId(this);">
</div>
<div id="div-3" onclick="storeId(this);">
</div>
<div id="div-4" onclick="storeId(this);">
</div>
<input>
解决方案
与其直接设置输入的值,不如将其存储id
在一个数组中,然后在每次单击时,用数组的内容更新输入。
此外,不要使用内联 HTML 事件属性。有很多理由不使用这种不会死的古老技术。
let ids = [];
$("div").on("click", function(){
// If the id is not already in the array, add it. If it is, remove it
ids.indexOf(this.id) === -1 ? ids.push(this.id) : ids.splice(ids.indexOf(this.id),1);
$('input').val(ids.join(", ")); // populate the input with the array items separated with a comma
});
div{
background-color:red;
height: 50px;
width:50px;
margin-bottom: 15px;
display:inline-block; /* Just for the SO space */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1"></div>
<div id="div-2"></div>
<div id="div-3"></div>
<div id="div-4"></div>
<input>
推荐阅读
- java - 最大堆大小无效:-Xmx4608m
- java - 如何在spring实体中仅定义选定的外部属性
- php - laravel 加载另一个 .env 文件并重新加载配置值
- neo4j - 将一个节点拆分为两个节点,然后删除原始节点
- kubernetes-helm - 如何正确选择舵伞图的尺寸
- javascript - React 中的 setState 没有更新我渲染的目录
- php - 多个产品未保存在 codeigniter 的 mysql 表中
- snowflake-cloud-data-platform - 雪花中的功能
- javascript - Javascript 变量和 HTML
- c# - 如何从 WPF 中的 DataGrid 中删除?