【问题标题】:How to update javascript array if item exists in that index position?如果项目存在于该索引位置,如何更新javascript数组?
【发布时间】:2017-07-20 20:17:41
【问题描述】:

对 jQuery 和 JavaScript 还很陌生,所以请保持温和...

我正在开发一个 POC 以创建一个“列映射”页面,用户可以在该页面中将“列标题”列表拖放到新列标题的网格中。我需要构建一个可以发送回 SQL 数据库的数组。我有这部分(大部分)按我的意愿运作。

当项目从左侧的列列表拖到右侧的标题网格时,如果项目存在,代码应该更新/替换该索引处的数组项目。如果该项不存在,则应将该项添加到数组中。

例如:如果将“First Name”拖到“Headers”,则应将其添加到索引位置 0。如果随后将“First Name”拖到“with”,则应删除索引 0 处的“First Name”值并在位置 1 添加值。如果然后将“Last Name”拖到“with”,它应该使用“Last Name”值更新位置 1 的数组。

$(document).ready(() => {
  $(function() {
    $('.item').draggable({
      cursor: "crosshair",
      cursorAt: {
        left: 5
      },
      distance: 10,
      opacity: 0.75,
      revert: true,
      snap: ".target",
      containment: "window"
    });
  });

  $(function() {
    var array = [];
    var arraytext = '';
    $('.target').droppable({
      accept: ".item",
      tolerance: 'pointer',
      activeClass: 'active',
      hoverClass: 'highlight',
      drop: function(event, ui) {
        var dropped = $(this);
        var dragged = $(ui.draggable);
        $(function(index, item) {
          var test = '';
          array.push($(dragged).text());
          arraytext = JSON.stringify(array);
          test += "Index Value = " + $(dropped).index() + ", Text = " + $(dragged).text() + "<br/>";
          $('#test').html(test);
          $('#array').text(arraytext);
        });
      }
    });
  });
});
#container {
  border: solid black 1px;
  margin: 0 auto;
  height: 800px;
}

#gridview {
  border: 2px solid #292da0;
  border-radius: 5px;
  background-color: #7577a3;
  display: grid;
  grid-template-columns: repeat(auto-fit, 100px);
  grid-template-rows: auto;
  margin-left: 105px;
}

.target {
  border: 2px solid #1c1c3a;
  border-radius: 5px;
  background-color: #a7a7ef;
  padding: 1em;
}

#flex {
  border: 2px solid #292da0;
  border-radius: 5px;
  width: 100px;
  background-color: #7577a3;
  display: flex;
  flex-flow: column wrap;
  justify-content: flex-end;
  float: left;
}

.item {
  border: 2px solid #1c1c3a;
  border-radius: 5px;
  background-color: #a7a7ef;
  padding: 1em;
}

.active {
  background-color: blue;
  color: white;
  border: 2px solid black;
}

.highlight {
  background-color: yellow;
  color: black;
  border: 2px solid blue;
}

.table {
  border: solid black 1px;
  width: 86px;
  padding: 5px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div id="container">
  Test:
  <div id="test">
  </div>
  Array:
  <div id="array">
  </div>
  <div id="gridview">
    <div class="target">Headers</div>
    <div class="target">with</div>
    <div class="target">different</div>
    <div class="target">column</div>
    <div class="target">names</div>
  </div>
  <span>
  <div id="flex">
    <div class="item">First Name</div>
    <div class="item">Last Name</div>
    <div class="item">Code</div>
    <div class="item">Date</div>
    <div class="item">Amount</div>
  </div>
   <table>
     <thead>
       <tr>
         <td class="table">Some</td>
         <td class="table">Column</td>
         <td class="table">Data</td>
         <td class="table">Goes</td>
         <td class="table">Here</td>
         </tr>
     </thead>
       <tr>
         <td class="table">Other Data</td>
         <td class="table">Other Data</td>
         <td class="table">Other Data</td>
         <td class="table">Other Data</td>
         <td class="table">Other Data</td>
       </tr>
   </table>
  </span>
</div>

JSFiddle:https://jsfiddle.net/qxwzcn9w/4/

最终,如果您发现任何危险信号或“陷阱”,我会将索引值发送回数据库,以便加分。谢谢!

【问题讨论】:

  • 看起来您只是将值推送到数组中。如果你改为添加这样的值:array[index] = value,那应该会给你你想要的。分配值之间的未分配索引将自动设置为未定义,因此数据库需要能够处理该问题,以及比预期短的数组。
  • 想法:什么是,如果您检查放置了哪个元素并在数组上设置(fe First Element)“名字”值为0,如果“名字”是拖动到“with”,“First Name”的数组值设置为 1。毕竟,提交按钮从数组中读取位置并将其发送到数据库。我希望这可以理解^^
  • @Chairs 感谢您的回复。我认为您正在解决问题。有没有办法根据gridview div中的元素数量创建具有多个索引/空字符串的数组?
  • @FalkeDesign 是的,完全正确。

标签: javascript jquery css json


【解决方案1】:

我个人会使用对象而不是数组,并使用索引作为对象的键

  var cols ={};

  $('.target').droppable({
    .....
    drop: function(event, ui) {
      var txt = $(ui.draggable).text(),
          colIdx = $(this).index();
      // clear from any prior position
      $.each(cols, function(key, val){
         if (val === txt){
           cols[key] = null
         }
      });
      // add to new position
      cols[colIdx] = txt;           

    }
  }).each(function(i){
     // add each index as key in cols object
     cols[i] = null;
  });

如果后端必须有数组,则在提交之前将 cols 对象映射到数组很简单

DEMO

【讨论】:

  • 在这种情况下使用对象与数组有什么好处?
  • 我不知道在这种情况下是否有真正的优势,但一般来说:在一个数组中,你正在访问相对于其他位置的某个位置,所以如果标题改变位置你必须改变阵列来弥补这一点。如果您使用键,那么您可以更改标题,并且不需要更改代码。
【解决方案2】:

使用 for 循环查找元素是否存在的简单解决方案。如果您对 jQuery 感到满意,也可以使用 $.each()。如果需要,您可以通过使用$("thead").find("td") 计算表头列来计算数组长度。然后像往常一样迭代查看该元素是否存在,如果存在则将其删除,然后插入到相应的索引中。

$(function() {
  $('.item').draggable({
    cursor: "crosshair",
    cursorAt: {
      left: 5
    },
    distance: 10,
    opacity: 0.75,
    revert: true,
    snap: ".target",
    containment: "window"
  });
});

$(function() {
  var arraytext = '';
  $('.target').droppable({
    accept: ".item",
    tolerance: 'pointer', 
    activeClass: 'active',
    hoverClass: 'highlight',
    drop: function(event, ui) {
      var dropped = $(this);
      var dragged = $(ui.draggable);
      $(function(index, item) {
        var test = '';

        for(var i = 0; i < array.length; i++)
        {
          if($(dragged).text() == array[i])
          {
            array[i] = "";
          }
        }
        array[$(dropped).index()] = $(dragged).text();
        arraytext = JSON.stringify(array);
        test += "Index Value = " + $(dropped).index() + ", Text = " + $(dragged).text() + "<br/>";
        $('#test').html(test);
        $('#array').text(arraytext);
      });
    }
  });
});

【讨论】:

    【解决方案3】:
    array.push($(dragged).text());
    

    这一行将删除的列推入数组,而不是更新它。

    您应该首先在某处初始化一个数组,其中每个列标题都为空值。

    var arr = Array.apply(null, new Array(10)).map(Number.prototype.valueOf,0);
    //console.log(arr) Outputs as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    

    将数字更改为您拥有的列数。

    要更改给定索引处的值,请执行以下操作:

    arr[3]='a new value';
    //console.log(arr) Outputs as [0, 0, 0, 'a new value', 0, 0, 0, 0, 0, 0]
    

    【讨论】:

    • new Array(10).fill(0); 创建一个 10 乘以 0 的数组看起来更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多