var array = [];
$('input').click(function(){
var value = this.value;
if (array.indexOf(value) > -1) {
array.splice(array.indexOf(value));
$(this).next('span').html('');
return false;
}
array.push(value);
$(this).next('span').html(array.indexOf(value));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='button' value="x">
<span></span>
</div>
<div>
<input type='button' value="y">
<span></span>
</div>
在我的脚本中,我在 input
之后的下一个 span
中插入 index
,所以当您单击 x
你得到 0
,当你点击 y
时,你得到 1
,反之亦然,问题是当我再次点击 x
其索引 = 0
,
我期望的是 y
的 span
更改为 0
而不是 1
因为 key 删除 x
索引后位置发生了变化,
但这并没有发生,跨度保持 1
但如果再次单击它,它会变为 0
,我该如何解决这个问题?
编辑:添加了 jQuery 标签
最佳答案
这是我使用 JQuery 更新所有内容的尝试。
Something to note is that the splice
function actually takes more arguments than just the index 。如果您不提供 length
参数,它将删除数组中索引之后的所有内容。
var array = [];
$('input').click(function(){
var value = this.value
var result = true;
var i = array.indexOf(value);
if (i > -1) {
array.splice(i, 1);
result = false;
} else {
array.push(value);
}
updateSpans();
return result;
})
function updateSpans(){
$("input").each( function(){
var i = array.indexOf(this.value);
var newHTML = i;
if (i == -1){
newHTML = "";
}
$(this).next('span').html(newHTML);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='button' value="x">
<span></span>
</div>
<div>
<input type='button' value="y">
<span></span>
</div>
关于javascript - 数组索引更改后重新排序元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49140310/