我有一个函数可以在各种div
的内容中进行冒泡排序。对于每个交换操作,它使用JQuery Swapsies plugin
交换div。问题是它是交换一次,然后是其他交换操作:
function swap(id1, id2){
$('#' +id1).swap({
target: id2,
opacity: "0.5",
speed: 1000,
callback: function() {
}
});
}
function bubbleSort() {
var ret=[];
$(".num-div").each(function(){ ret.push($(this));});
let swapped;
do {
swapped = false;
for (let i = 1; i < ret.length; ++i) {
if (ret[i - 1].html() > ret[i].html()) {
swap(ret[i-1].attr('id'), ret[i].attr('id'));
[ret[i], ret[i - 1]] = [ret[i - 1], ret[i]];
swapped = true;
}
}
} while (swapped);
return ret;
}
在i=1
工作的第一步中,将ret[i-1]
与ret[i]
交换,但之后无效。
答案 0 :(得分:1)
swap
插件在忙于动画时不会处理呼叫。您可以在插件的source code中看到:
if (options.target!="" && !swapping) {
正在进行的动画期间,swapping
变量将为true
,if
将跳过任何新动画,恕不另行通知。
无论如何,您可能希望动画按顺序发生,而不是所有动画同时发生。为此,我建议使用promises和相当新的async/await
语法。
首先,您将宣传swap
函数,因此它会返回一个承诺。然后,您可以在适当的位置添加async
和await
个关键字,并且......它会起作用。
还有一点需要注意:如果您的数据是数字,并且您想要按数值排序,则需要在进行比较之前将字符串转换为数字,例如通过应用这样的一元+
:{{ 1}}
这是一个有效的演示:
+ret[i].text()
&#13;
function swap(id1, id2){
return new Promise(resolve =>
$('#' +id1).swap({
target: id2,
opacity: "0.5",
speed: 500,
callback: resolve
})
);
}
async function bubbleSort() {
var ret=[];
$(".num-div").each(function(){
ret.push($(this));
});
let swapped;
do {
swapped = false;
for (let i = 1; i < ret.length; ++i) {
if (ret[i - 1].text() > ret[i].text()) {
await swap(ret[i-1].attr('id'), ret[i].attr('id'));
[ret[i], ret[i - 1]] = [ret[i - 1], ret[i]];
swapped = true;
}
}
} while (swapped);
return ret;
}
bubbleSort().then( ret => {
console.log($.map(ret, x => $(x).text()));
});
&#13;