Jquery 可排序 - 从数据库检索元素位置并在刷新时将每个元素放置到其自己的位置

问题描述 投票:0回答:1

我一直在尝试使用 jquery 可排序为我的龙与地下城会话制作一个带有棋子(类似国际象棋)的简单网格系统。我正在使用 Laravel 和 Blade 来完成一个小项目。它不会投入生产或其他什么,所以此时一切都会进行。

所以在下面的代码中(这是我做的另一个问题给我的)它创建了一个特定区域的网格,玩家可以在其中自由移动棋子。我这样做是为了让 ajax 请求可以将每个 pawn 的坐标以 0,1 3,4 等形式保存到数据库中。

通常一切正常,但问题是我无法将每个 pawn 的位置保持在网格中,因此当页面重新加载时,pawn 将到达其初始坐标。不仅如此,如果我不明白这一点,我就无法做到这一点,这样其他玩家就会看到棋子坐标。

这是我到目前为止得到的代码:

let gridSize = 7,
//characters array is empty usually because it gets all the pawn infos from the db
     characters = [ {"id" : "1" , "name" : "Test", "hp" : "112"}
     ];

$('.grid')
  .css(`grid-template-columns`, `repeat(${gridSize}, 4rem)`)
  .html([...Array(gridSize**2)].map(() => '<div class="cell"></div>').join(''));

$('.characters')
  .html(characters.map((character) =>
    `<div class="character"><div class="stats" id ='${character.id}'><p>${character.name}</p><p>hp: ${character.hp}</p></div></div>`).join(``))
  .add('.grid .cell')
  .sortable({
    connectWith: '.characters, .grid .cell',
    cursor: 'grabbing',
    receive: (e, ui) => {
      if(ui.item.parent().hasClass('cell')) {
        let $cell = $(e.target),
            $character = ui.item,
            $characters = $cell.find('.character').not($character),
            coords = [$cell.index() % gridSize, Math.floor($cell.index() / gridSize)];
            coords = coords.toString();
            let characterId = $character.find('.stats').attr('id');
            updateCharacterPosition(characterId, coords)//writes the new pawn's position to the db
            
      }
    }
  });

  function updateCharacterPosition(characterId, coords) {


$.ajax({


    url: "/coords/" + characterId,
    method: 'PATCH',
    data: {
      _token: $('meta[name="csrf-token"]').attr('content'),
        newcoords: coords
    },
    success: function(response) {
        console.log('Character position updated successfully');
    },
    error: function(xhr, status, error) {
        console.error('Error updating character position:', error);
    }
});
}
   .grid{
  border: 2px solid gray;
  display: grid;
  width: fit-content;}
  
.grid .cell{
  align-items: center;
  aspect-ratio: 1 / 1;
  border: 1px solid lightgray;
  display: flex;
  justify-content: center;
  overflow: visible;}
  
.grid .cell:has(.character):hover{
  border-width: 2px;
  box-sizing: border-box;}
  
.characters{
  border: 2px solid gray;
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  min-height: 3rem;
  min-width: 6rem;
  padding: 1rem;
  width: fit-content;}
 
.character{
  align-items: end;
  background-color: #000000;
  border-radius: 50%;
  color: #ffffff;
  display: flex;
  height: 3rem;
  justify-content: center;
  text-align: center;
  width: 3rem;}
  
.character .stats{
  background-color: inherit;
  padding: 4px;}

.character p{
  font-size: .66rem;
  margin: 0;
  white-space: nowrap;}
<div class="grid"></div>
<div class="characters"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

javascript jquery jquery-ui-sortable
1个回答
0
投票

如果您想使棋子在刷新时保持在坐标中,您可以使用

localStorage.setItem("PawnX", "5");
localStorage.setItem("PawnY", "5");

设置本地存储,然后就可以使用了

string PawnXString = localStorage.getItem("PawnX");
string PawnYString = localStorage.getItem("PawnY");

要从本地存储获取它,并将其转换回 int,你可以这样做

int PawnX = parseInt(PawnXString);
int PawnY = parseInt(PawnYString);
© www.soinside.com 2019 - 2024. All rights reserved.