多个图像选择 - 如何在选择时取消选择?

时间:2017-11-08 09:04:50

标签: jquery html

我目前正在进行多个图像选择,如果选择了图像,则需要取消选择该图像。我目前正在使用.find查找已存在的值,如果找到则将其替换为空白。

  

HTML:

<input type="text" name="selectg" id="selectg" /><img src="#"  class="col-sm-3 thumbnail imgSel" data-value="gift1" /><img src="#" class="col-sm-3 thumbnail imgSel"  data-value="gift2" /><img src="#"  class="col-sm-3 thumbnail imgSel"  data-value="gift3" /><img src="#"  class="col-sm-3 thumbnail imgSel"  data-value="gift3" /><img src="#"  class="col-sm-3 thumbnail imgSel" data-value="gift4" />
  

脚本:

$(".imgSel").click(function(){

            var tmp = $("#selectg").val();

            id = $(this).data("value");

            // do a detection if the id is in the input field(selectg)
            var x = id
            var y = $(this).data('value');
            var h = $('id').find(y).length;
            console.log(h)

            if (h>1) {
                var z = x.text().replace(y, '');
                 console.log(z)
                 x = z
                 console.log(x)
             }

             else{
                id = (tmp)?id+","+tmp:id;
             }

            $("#selectg").val(id);

            if($(this).hasClass('selected')) {
                $(this).removeClass('selected');
            }
            else {  
                $(this).addClass('selected');
            }

        });

1 个答案:

答案 0 :(得分:0)

我有点不确定你想要的是什么,但请尝试下面的代码。如果它不是你想要的,请澄清你想要的东西。

&#13;
&#13;
$(".imgSel").click(function() {

  var tmp = $("#selectg").val();

  id = $(this).data("value");

  // do a detection if the id is in the input field(selectg)
  var x = id
  var y = $(this).data('value');
  var h = tmp.split(',').indexOf(y);
  console.log(h)

  if (h > -1) {
    id = tmp.replace("," + y, "").replace(y+",","").replace(y,"");
  } else {
    id = (tmp) ? id + "," + tmp : id;
  }

  $("#selectg").val(id);

  if ($(this).hasClass('selected')) {
    $(this).removeClass('selected');
  } else {
    $(this).addClass('selected');
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="selectg" id="selectg" />
<img src="#" class="col-sm-3 thumbnail imgSel" data-value="gift1" alt="gift1" />
<img src="#" class="col-sm-3 thumbnail imgSel" data-value="gift2" alt="gift2" />
<img src="#" class="col-sm-3 thumbnail imgSel" data-value="gift3" alt="gift3" />
<img src="#" class="col-sm-3 thumbnail imgSel" data-value="gift3" alt="gift3" />
<img src="#" class="col-sm-3 thumbnail imgSel" data-value="gift4" alt="gift4" />
&#13;
&#13;
&#13;