多个div选择onclick

时间:2018-06-12 20:43:25

标签: javascript jquery html css

我有多个div与他们的id,并且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>

3 个答案:

答案 0 :(得分:3)

不是直接设置输入值,而是将id存储在数组中,然后在每次单击时,使用数组的内容更新输入。

此外,请勿使用内联HTML事件属性。有 many reasons 不使用这种不会死的古老技术。

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>

答案 1 :(得分:1)

根据您的要求,您有两种选择:

  1. 将新点击的ID附加到您输入的现有值。
  2. 将新点击的ID推送到一个用于构建输入值的数组中。
  3. 选项1

    function storeId (el) {
       var currentValue = $('input').val();
       $('input').val(currentValue + ', ' + el.id);
    }
    

    (或者使用更新的语法)

    function storeId (el) {
       const currentValue = $('input').val();
       $('input').val(`${currentValue}, ${el.id}`);
    }
    

    选项2

    var storedIds = [];
    function storeId (el) {
       var index = storedIds.indexOf(el.id);
       if (index === -1) {
          storedIds.push(el.id);
       } else {
          storedIds.splice(index, 1);
       }
    
       $('input').val(storedIds.join(', '));
    }
    

    编辑:只有上面的数组示例检查是否已存储正在存储的ID。

答案 2 :(得分:-1)

请尝试一下:

[ 71%] Linking CXX executable pdftohtml 
    /usr/bin/ld: CMakeFiles/xpdf_objs.dir/Gfx.cc.o: undefined reference to symbol 'acos@@GLIBC_2.2.5'
    //usr/lib64/libm.so.6: error adding symbols: DSO missing from command line
    collect2: error: ld returned 1 exit status
    make[2]: *** [xpdf/CMakeFiles/pdftohtml.dir/build.make:219: xpdf/pdftohtml] Error 1
    make[1]: *** [CMakeFiles/Makefile2:428: xpdf/CMakeFiles/pdftohtml.dir/all] Error 2
    make: *** [Makefile:130: all] Error 2
相关问题