首页 > 解决方案 > 多个 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>

标签: javascriptjqueryhtmlcss

解决方案


与其直接设置输入的值,不如将其存储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>


推荐阅读