【问题标题】:How to add/remove element in an array on click?如何在单击时添加/删除数组中的元素?
【发布时间】:2021-07-19 02:54:00
【问题描述】:

如何在单击座位时防止重复,这样当我再次单击它时它不会附加,而是连续删除/添加。

  var ids = [];
  $seatid = ids;
  var status = "unavailable";

  $(document).ready(function() {
    var $div = $("<div id='form'></div>").appendTo(".appended"), code;

      $('.seat').click(function(){
        var id = jQuery(this).attr("id");

        if ($(this).hasClass('available')){
          code = jQuery(this).attr("id");
          ids.push(code);
          $div.append(code + "<br />");
          console.log(code);

        }else{
          console.log('Failed');
          console.log(id);
        }                        
      });
  });

see pic of the output

【问题讨论】:

  • 您没有向我们提供足够的信息来帮助您。请查看为什么以及如何创建minimal reproducible example,强调最小化。在编辑器中使用 按钮创建一个 sn-p。

标签: javascript php jquery arrays


【解决方案1】:

推送新 ID 后,您需要删除“可用”类。我不太熟悉 JQuery,但它看起来像这样:

if ($(this).hasClass('available')){
      code = jQuery(this).attr("id");
      ids.push(code);
      $div.append(code + "<br />");
      console.log(code);
      //REMOVE AVAILABLE CLASS
      $(this).removeClass("available");
    }

您可能需要在运行 else 语句时重新添加课程(假设您希望在单击时将“不可用”座位变为“可用”)。

当您从“不可用”(在数组中)变为“可用”(不在数组中)时,您还需要一些逻辑来从数组中删除座位 ID

【讨论】:

    【解决方案2】:

    您可以使用 Jquery 的 toggleClass() 函数来做到这一点。

    例如,如果你想删除或添加类“可用”和“选择”,下面的代码会很好。

    $('#x').click(function(){
      $('#x').toggleClass('available').toggleClass('selected');
    })
    

    此外,如果您想从数组中删除项目。您可以使用以下代码。

    const array = [12, 34, 10];
    
    const index = array.indexOf(12);
    if (index > -1) {
      array.splice(index, 1);
    }
    
    // array = [34, 10]
    console.log(array);
    

    最后,你的代码应该更新如下..

    var ids = [];
    $seatid = ids;
    var status = "unavailable";
    
    $(document).ready(function() {
    var $div = $("<div id='form'></div>").appendTo(".appended"), code;
    
      $('.seat').click(function(){
        var id = jQuery(this).attr("id");
        if ($(this).hasClass('available')){
            code = jQuery(this).attr("id");
            ids.push(code);
            $div.append(code + "<br />");
        } else {
            const index = ids.indexOf(code);
            if (index > -1) {
              ids.splice(index, 1);
            }
            console.log('Failed');
            console.log(id);
        }                        
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 2020-10-08
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多