问题描述
我正在尝试使用HTML,CSS和JS(jQuery)创建气泡排序算法。想法是交换项目的高度,以按高度(obvs)对它们进行排序。
不知何故,我的代码使我陷入了无限循环。我希望有人可以帮助我确定问题所在。提前谢谢!
var el = $('#item_parent');
var items = [];
//Genrate elements
for(let i = 0; i < 5; i++){
let rand = Math.floor(Math.random() * 300) + 1;
el.append("<div class='item d-flex justify-content-between' data-height='"+rand+"' style='height: "+rand+"px; flex: 1; margin: 0 5px;'></div>");
}
//Populating the array with the elements
items = $(".item");
var sorted = false;
while(!sorted){
sorted = true;
for (let i = 0; i < items.length - 1; i++){
if ($(items[i]).data('height') > $(items[i+1]).data('height')){
console.log($(items[i]).data('height') + " is greater than " + $(items[i+1]).data('height') + ". Swapping");
swapHeight(items,i,i+1);
sorted = false;
}
}
}
function swapHeight(elArray,firstIndex,secondindex){
let temp = $(elArray[firstIndex]).data('height');
$(elArray[firstIndex]).css('height',$(elArray[secondindex]).data('height') + "px");
$(elArray[secondindex]).css('height',temp + "px");
}
解决方法
您正在阅读foo('US')
foo('US','CA','UK')
foo(['US','UK'])
,但正在写作params
。
这只是关于.data('height')
和.css('height')
之间的关系的次要脸部表情(不用担心,我们每个人早上咖啡因水平不足)。它们是完全不同的东西。
您的.data('height')
不会交换您正在比较的.css('height')
,并且事情会无限循环地进行。
JQuery在内部存储其swapHeight
,而不是元素CSS样式中的高度。参见Where is jQuery.data() stored?