我希望此click事件检查项目是否在数组中。如果是,请将其删除。如果没有,请将其添加回同一位置。
var myArray = ["apple","orange","pear","grape"];
$("button").click(function(){
if($.inArray(apple,myArray) != -1){
myArray.push(apple,1);
} else {
myArray.splice(apple,1);
}
alert(myArray);
});
答案 0 :(得分:0)
myArray.push("apple");
myArray.splice(lastRemovedIndex, 0, "apple");
if($.inArray(apple,myArray) != -1)
更改$.inArray("apple", myArray) == -1
。myArray.splice(myArray.indexOf("apple"), 1);
删除元素。"
周围的apple
。
var myArray = ["apple", "orange", "pear", "grape"];
var lastRemovedIndex = -1;
$("#myBtn").click(function() {
if ($.inArray("apple", myArray) == -1) {
myArray.splice(lastRemovedIndex, 0, "apple");
} else {
var i = myArray.indexOf("apple");
myArray.splice(i, 1);
lastRemovedIndex = i;
}
alert(myArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myBtn">Click me</button>