我正在用javascript制作一个拖放工具。我有一个图像集合,我可以拖放到一个网格。这个网格有3行20列。
当一个图像被拖到网格上时,我想保存这个数据。例如,我将图像拖放到第1行第2列中,如何将这些数据保存在javascript中?
在php中,这将是:
<?php
// row 1, column 2
$savedItems[1][2] = array("image" => "testimage.jpg", "extra" => 1);
?>这样我就可以检查是否已经有图像在那个地方。或者,如果我想更改spot的选项,我可以在$savedItems数组中搜索。
但是如何将这些数据保存在javascript中呢?因此,可以很容易地在数组中添加和搜索数据。
发布于 2015-08-07 08:54:38
在JavaScript中几乎完全一样。
var cells = [ [ ], [ ], [ ] ];
function insertImage(row, column, image) {
if (cells[row][column]) {
console.info('Already exists!');
return false;
} else {
cells[row][column] = image;
return true;
}
}发布于 2015-08-11 06:17:12
无论何时执行拖放,都必须知道要拖放的行和列的索引。执行拖放时,调用像saveValues(rowIndex、columnIndex、value)这样的函数,将位于该位置的值保存到数组中。在保存之前,请检查位置是否已经有一些除默认值之外的数据。如果是,请不要保存值和中断,以便不会执行拖放,否则保存值,然后执行拖放。
假设您的数组名为: dragDropGrid
function saveValues(rowIndex, columnIndex , value) {
// value here is something related to that image .
var valueAtIndex = dragDropGrid[rowIndex][columnIndex] ;
if(valueAtIndex != null || valueAtIndex != "" || valueAtIndex != undefined ) {
// If there already exists a value
return false; // something to break the drag drop
}else{ // if array location is empty
dragDropGrid[rowIndex][columnIndex] = value; //saved value at that index.
return true; // now call drag drop.
}
}您可以在执行dragDrop之后,在某些事件上直接调用此函数。确保函数返回正确,以便继续或中断拖放。
谢谢
发布于 2015-08-07 19:00:20
您可以将$savedItems打印为javascript全局变量。
<?php
echo '<script>';
echo 'var saved_items = ' . json_encode($savedItems); . ';';
echo '</script>';https://stackoverflow.com/questions/31873440
复制相似问题