當用戶單擊表格中的某個塊(請參閱屏幕截圖)時,我想查找具有相同顏色的所有相鄰塊。我試圖遞歸地做到這一點,但如果我嘗試使用三塊以上的塊,它有時會變得瘋狂並且一遍又一遍地調用自身,直到程序崩潰。用於遍歷網格的遞歸函數變得瘋狂
據我所看到的,這些對象被添加到數組中,但不知何故,我的測試失敗並且一遍又一遍地添加相同的對象。
任何有關這個問題可能的解決方案以及如何解決這個問題都會受到很大的關注!
這裏有一個screenshot
這是調用的函數,當用戶點擊一個塊:
var $matchArray;
$('.block').click(function() {
$matchArray = [$(this)];
var $colorClass;
if ($(this).hasClass('red')) {
$colorClass = 'red';
} else if ($(this).hasClass('green')) {
$colorClass = 'green';
} else if ($(this).hasClass('blue')) {
$colorClass = 'blue';
} else {
$colorClass = 'error';
}
findAllSameColorNeighbours($(this), $colorClass);
});
這是遞歸方法:
findAllSameColorNeighbours = function ($this, $colorClass) {
$this.css('border-style', 'solid');
//LEFT
var $leftBlock = isLeftBlockSameColor($this, $colorClass);
if ($leftBlock != null) {
if (!(arrayContains($matchArray, $leftBlock))) {
$matchArray.push($leftBlock);
findAllSameColorNeighbours($leftBlock, $colorClass);
}
}
//ABOVE
//same as for LEFT
//RIGHT
//same as for LEFT
//BELOW
//same as for LEFT
}
這是怎麼了我發現鄰近的細胞,據我所見,這些工作很好。我有一個爲每個方向:
isLeftBlockSameColor = function ($block, $color) {
var $this = $block;
var $tr = $this.parent().parent();
var col = $tr.children().index($this.parent().prev());
var $leftBlock = $this.parent().siblings().eq(col).children();
var $blockClassMatch = $leftBlock.hasClass($color);
if ($blockClassMatch) {
return $leftBlock;
}
else {
return null;
}
};
這裏有一些幫助方法,以找出是否該對象已在陣列中或沒有。我使用行和單元格的索引來創建一種緯度和長度的東西。
arrayContains = function ($array, $object) {
for (i = 0; i < Array.length; i++) {
if (compareIndex($array[i], $object)) {
say('true');
return true;
}
};
return false;
};
compareIndex = function ($obj1, $obj2) {
if ((getRowIndex($obj1)) === (getRowIndex($obj2)) {
if ((getCellIndex($obj1)) === (getCellIndex($obj2)) {
return true;
} else {
return false;
}
} else {
return false;
}
};
getCellIndex = function ($this) {
var $tr = $this.parent().parent();
var index = $tr.children().index($this.parent());
return index;
};
getRowIndex = function ($this) {
var $tr = $this.parent().parent();
var index = $tr.index();
return index;
};
你應該提供一個代碼片段或複製的jsfiddle您的問題 –
@PeCeSe,我會建議使用jQuery的查找替換遞歸的邏輯。當然,你不能直接做到這一點。嘗試按類設置顏色,並使用「find」來查找類。 OMG !!! – Lordbalmon