我之前已经问过类似的问题,但是我尝试了每一个答案,对我来说没有任何作用。我使用array
在buttons
的某些点击上创建了我的class ognjen
。所以它看起来像这样:
<button type="button" name="10208823390691752,1317727711586522" value="All contacts" class="btn btn-default ognjen">All contacts</button>
<button type="button" name="10207252567926988,1294280923934896" value="Men" class="btn btn-default ognjen">Men</button>
<button type="button" name="10208823390691752,10207252567926988" value="Women" class="btn btn-default ognjen">Women</button>
<button type="button" name="1317727711586522,1294280923934896" value="Segment 1" class="btn btn-default ognjen">Segment 1</button>
所以这就是我设法制作一个包含所有点击元素值的数组:
$(document).ready(function() {
var clickedButtons = new Array();
var numUsers= new Array();
$('button.ognjen').click(function() {
var index = clickedButtons.indexOf(this.value);
if (index === -1){
clickedButtons.push(this.value);
numUsers.push(this.name);//value not found so push it
}else {
clickedButtons.splice(index, 1);
numUsers.splice(this.name);// value found so remove it
}
var tryIt=numUsers.join();
var picker=tryIt.split(', ');
console.log(picker);
});
所以picker
现在是一个可能看起来像这样的数组,点击某些按钮后:
["10207252567926988,1294280923934896,10208823390691752,1317727711586522,1294280923934896"]
现在,我想从此数组中删除所有重复的元素。从这些问题中找到了答案:
这些都没有奏效。我认为这可能是由于制作这个piker
数组的动态。请帮忙,我整天都在努力解决这个问题。
答案 0 :(得分:1)
我认为更简单的方法是存储每个按钮的点击状态,然后每次重新创建数组
$(document).ready(function() {
var clickedButtons = new Array();
var numUsers = new Array();
var $btns = $('button.ognjen').click(function() {
$(this).toggleClass('selected');
clickedButtons = new Array();
$btns.filter('.selected').each(function() {
var values = this.value.split(',');
values.forEach(function(value) {
var index = clickedButtons.indexOf(value);
if (index === -1) {
clickedButtons.push(value);
}
});
});
console.log(clickedButtons)
snippet.log(clickedButtons.join() || 'NONE');
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<button type="button" value="10208823390691752,1317727711586522" class="btn btn-default ognjen">All contacts</button>
<button type="button" value="10207252567926988,1294280923934896" class="btn btn-default ognjen">Men</button>
<button type="button" value="10208823390691752,10207252567926988" class="btn btn-default ognjen">Women</button>
<button type="button" value="1317727711586522,1294280923934896" class="btn btn-default ognjen">Segment So
&#13;