如何使用按钮切换从数组添加/删除对象?

时间:2018-08-30 21:48:21

标签: jquery

我写了以下代码,它向数组中添加了项,并且做到了这一点,所以我们不能在其中添加重复的对象,但是我想要实现的是如果我们再次单击添加的项实际上是添加/删除。 :

  var countryArray = [];
  var countryName = " ";
  $("#africa, #europe, #asia, #america").on("click", function() {
    countryName = $(this).attr("id");
    countryArray.push(countryName);
    $("span").attr("data-country", $.unique(countryArray.sort()));
  });

4 个答案:

答案 0 :(得分:1)

var countryArray = [];
var countryName = " ";
$("#africa, #europe, #asia, #america").on("click", function() {
  countryName = $(this).attr("id");

  let itemPos = countryArray.indexOf(countryName);
  if (itemPos < 0)
    countryArray.push(countryName);
  else 
    countryArray.splice(itemPos, 1)
  $("span").attr("data-country", $.unique(countryArray.sort()));
});

答案 1 :(得分:1)

因为 data-country 是一个数据属性,所以我建议将countryArray转换为对象。

这样,代码将是:

var countryArray = {};
var countryName = " ";
$("#africa, #europe, #asia, #america").on("click", function() {
    if (countryArray[this.id] === undefined) {
        countryArray[this.id] = true;
    } else {
        delete countryArray[this.id];
    }
    $("span").data("country", countryArray);
    console.log(Object.keys(countryArray).join(', '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="africa">africa</button>
<button id="europe">europe</button>
<button id="asia">asia</button>
<button id="america">america</button>
<span></span>

答案 2 :(得分:0)

请检查阵列中是否存在键,而不是每次都推入阵列,splice(从阵列中移出键)。

var countryArray = [];
var countryName = " ";
$("#africa, #europe, #asia, #america").on("click", function() {
    countryName = $(this).attr("id");
    let index = countryArray.indexOf(countryName);
    if (index >= 0) {
        countryArray.splice(index, 1);
    } else {
        countryArray.push(countryName);
    }
    console.log(countryArray.sort());
    $("span").attr("data-country", countryArray.sort());
});
div {
  display: inline-block;
  width: 50px;
  height: 50px;
}
#africa {
  background: red;
}
#europe {
  background: green;
}
#asia {
  background: blue;
}
#america {
  background: black;
}

.as-console-wrapper {
  width: 100%;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="africa"></div>
<div id="europe"></div>
<div id="asia"></div>
<div id="america"></div>

答案 3 :(得分:0)

通过添加.splice(index, itemsNum)(要删除索引中的项目),您可以删除$.unique
通过使用类(而不是ID),您将拥有更大的ID自由度

var arr = [];

$(".btn").on("click", function() {

  var i = arr.indexOf(this.id);
  i>-1 ? arr.splice(i, 1) : arr.push(this.id);
  $("span").attr("data-country", arr.sort());
  
});
span:after { content: attr(data-country); }
<button class="btn" id="africa">africa</button>
<button class="btn" id="europe">europe</button>
<button class="btn" id="asia">asia</button>
<button class="btn" id="america">america</button>
<span data-country=""></span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>