【问题标题】:Jquery - Adding and removing items from arrayJquery - 从数组中添加和删除项目
【发布时间】:2017-01-29 01:23:49
【问题描述】:

我希望这个点击事件检查该项目是否在数组中。如果是,请将其删除。如果没有,请将其添加回同一位置。

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);
});

【问题讨论】:

    标签: arrays


    【解决方案1】:
    • 将最后删除的索引存储在外部变量中。
    • 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>

    【讨论】:

    • 如何让苹果回到数组中的同一位置?
    • 此方法适用于作用于特定元素的切换按钮。如果元素可以更改,您必须跟踪对象中每个最后删除的索引var lastRemovedIndexes = { "apple": 1, "orange": 2 };
    猜你喜欢
    • 2017-09-13
    • 2021-10-03
    • 1970-01-01
    • 2014-12-23
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多