如果数据相关数字有序,则将div替换为另一个 [英] Replace div with another if data-rel numbers are in order
问题描述
我创建了一个谜题,我希望它能够 fadeOut
并将整个图像转换为 fadeIn
正确完成后,我在html中为每个拼图添加了一个带有数字的 data-rel
,这样我就能以某种方式找出拼图正确完成的时间,但我没有关于如何做到这一点的想法。
I have a puzzle created and I want it to fadeOut
and the entire image to fadeIn
when the puzzle is finished correctly, I have added a data-rel
with numbers to each piece of the puzzle in html so that I can somehow find out when the puzzle is correctly completed but I have no idea on how to do this.
我想我可以使用类似 replaceWith
之类的东西:
I think I can use something like replaceWith
like so:
$( this ).replaceWith( "<div>" + "my-full-image-source" + "</div>" );
但是,只有当数据相关数量符合规定时,我该如何触发?
这是我的HTML:
<div id="shell">
<div class="puzzle" data-rel="10">10</div>
<div class="puzzle" data-rel="1">1</div>
<div class="puzzle" data-rel="4">4</div>
<div class="puzzle" data-rel="7">7</div>
<div class="puzzle" data-rel="11">11</div>
<div class="puzzle" data-rel="2">2</div>
<div class="puzzle" data-rel="5">5</div>
<div class="puzzle" data-rel="8">8</div>
<div class="puzzle" data-rel="12">12</div>
<div class="puzzle" data-rel="6">6</div>
<div class="puzzle" data-rel="9">9</div>
<div class="puzzle" data-rel="3">3</div>
</div>
脚本:
$(document).ready(function () {
$('#shell').sortable({cursor: 'move'});
});
此外 jsFiddle 以便于理解。
提前感谢任何建议。
推荐答案
在这里:
http://jsfiddle.net/lotusgodkk/gtFMD/2/
方法是将解决方案存储为数据的数组-rel
。并在 sortable的
。然后比较这两个数组/如果它们相等则可以进行必要的更改/修改。更新
函数中获取已排序项目的 data-rel
数组
Approach is to store the solution as an array of data-rel
. And get the array of sorted item's data-rel
in the update
function of sortable
. And then compare those two arrays/ If they are equal then you can do the necessary changes/ modifications.
JS:
$(document).ready(function () {
var key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; //Answer
$('#shell').sortable({
cursor: 'move',
update: function (event, ui) {
var numbers = $('.puzzle[data-rel]').map(function () {
return parseInt($(this).attr('data-rel'));
});
console.log(numbers);
if (key.equals(numbers)) {
alert('done'); // Your code here
}
}
});
});
//For array comparison.
Array.prototype.equals = function (array) {
if (!array) return false;
if (this.length != array.length) return false;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].equals(array[i])) return false;
} else if (this[i] != array[i]) {
return false;
}
}
return true;
}
对于数组比较:如何在JavaScript中比较数组?
这篇关于如果数据相关数字有序,则将div替换为另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!