简体   繁体   English

使用jquery拖动元素,获取div的索引,该索引在其停止和开始位置

[英]Dragging elements with jquery, get index of div where it stops and where it starts

I am trying to implement a board game (with a chess-like board) where I have a pawn that I can drag over the board on a grid made of divs: 我正在尝试实现一个棋盘游戏(使用类似国际象棋的棋盘),其中有一个棋子,可以在由divs组成的网格上拖动棋盘:

<div id="table">
    <div class="table_header" id ="table_header_top"> </div>
    <div class="separation" id="separacion_top"> </div>
    <div id="table_body"> </div>
    <div class="separation" id="separacion_bottom"> </div>
    <div class="table_header" id ="table_header_bottom"> </div>
</div>

Script: I make an array with the cells of the table and then appends the cells to the table. 脚本:我用表的单元格组成一个数组,然后将这些单元格附加到表中。 This is just the relevant part of it: 这只是其中的相关部分:

var table= []
var table_body = document.getElementById("table_body")
for(var f=1; f<=9;f++){
    for(var c=0;c<=8;c++){
        var cell = document.createElement("DIV");
        table_body.appendChild(cell);
        table.push(cell);
    }
}

    $(black_pawn).draggable({
        containment: $('#table_body'),
        grid:[70,70],
    })

The table is rather big (11x11), and I want to get the index of the cell where I drop the pawn in my array. 该表很大(11x11),我想获取将典当放到数组中的单元格的索引。 In the end, I want to do this to check if the move was valid, ie, if the pawn moved a valid ammount of spaces in the table. 最后,我要执行此操作以检查移动是否有效,即典当是否移动了表中的有效空间。 So I need to get the index where the pawn starts and where the pawn stops after dragging. 因此,我需要获取拖动后典当开始和典当停止的索引。

All help is greatly appreciated. 非常感谢所有帮助。

PS: I know that jquery allows me to find the coordinates of the stoping position. PS:我知道jquery允许我找到停止位置的坐标。 But I want to identify the div where it stops, not the coordinates. 但是我想确定它停止的div,而不是坐标。 I understand that I could make a function that translates coordinates to indexes of divs, but I think there should be a simpler way. 我知道我可以创建一个将坐标转换为div索引的函数,但是我认为应该有一种更简单的方法。

I think you should look into using 'droppable' from jQuery as well ( https://jqueryui.com/droppable/ http://api.jqueryui.com/droppable/ ). 我认为您也应该考虑使用jQuery中的“可放置”( https://jqueryui.com/droppable/ http://api.jqueryui.com/droppable/ )。 It will allow you to use the 'over' and 'drop' events. 它将允许您使用'over'和'drop'事件。 Correct me if I'm wrong, but I think you will be able to get the droppable element with these events. 如果我错了,请纠正我,但是我认为您可以通过这些事件获得droppable元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM