通过单击附加选定的值

时间:2018-06-26 13:00:39

标签: javascript jquery html arrays

$("#select-estate").change(function() {
  var singleValues = $("#select-estate").val();
  if (estate.includes(singleValues) == false) {
    estate.push(singleValues);
    $("span.filter-push-select").append('<label class="active">' + singleValues + '<i class="fa fa-times fa-lg" aria-hidden="true"></i></label>');
    console.log(estate);
  }
});
$(".filter-push-select").on('click', 'label', function() {
  var item = $("#select-estate").val();
  var iterator = estate.keys();
  for (let key of iterator) {
    console.log(key); // expected output: 0 1 2
  }

  function removeItem(estate, item) {
    for (var i in estate) {
      if (estate[i] == item) {
        break;
      } else {
        estate.splice(i, 1);
      }
    }
  }
  removeItem(estate, item);
  $(this).remove();
  //estate.splice(index, 1);

  console.log(estate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="increase" class="form-control" id="select-estate">
  <option disabled selected value="Select">Estate Type</option>
  <option value="ownership">ownership</option>
  <option value="rent">Rent</option>
</select>
<span class="filter-push-select"></span>

我在此函数上遇到问题,我需要从数组中删除我选择的值。

当我选择一个值并单击以将其从标签中的数组中删除时,将其正确删除,但是当我选择多个值并尝试从附加标签中将其删除时,在删除该值中从数组中单击时是错误的

2 个答案:

答案 0 :(得分:0)

我不太确定您要做什么,但是请在下面检查我的答案,看看是否可以解决问题。

var estates = []
$("#select-estate").change(function() {
  var singleValues = $("#select-estate").val();
  if (estates.includes(singleValues) == false) {
    estates.push(singleValues);
    $("span.filter-push-select").append('<label class="active">' + singleValues + '<i class="fa fa-times fa-lg" aria-hidden="true"></i></label>');
    console.log(estates);
  }
});

$(".filter-push-select").on('click', 'label', function() {
  var item = $("#select-estate").val();
  var iterator = estates.keys();
  for (let key of iterator) {
    console.log(key); // expected output: 0 1 2
  }

  function removeItem(estate, item) {
    for (var i in estate) {
      if (estates[i] == item) {
        estates.splice(i, 1);
      }
    }
  }
  
  removeItem('ownership', item);
  $(this).remove();

  console.log(estates);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="increase" class="form-control" id="select-estate">
  <option disabled selected value="Select">Estate Type</option>
  <option value="ownership">ownership</option>
  <option value="rent">Rent</option>
</select>
<span class="filter-push-select"></span>

答案 1 :(得分:0)

如果我正确地提出了问题,那么这将解决问题。问题不在于拼接位,而是在于单击了适当的标签元素文本值。 (<script type="text/javascript" src="/home/baron1/Dropbox/github/html2canvas/dist/html2canvas.js"></script> <script type="text/javascript"> html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); </script>

var item = $(this).text();