Replace div with another if data-rel numbers are i

2019-08-14 05:56发布

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.

I think I can use something like replaceWith like so:

$( this ).replaceWith( "<div>" + "my-full-image-source" + "</div>" );

But how do i trigger this only if the data-rel numbers are in order?

Here is my 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>

And the script:

$(document).ready(function () {
    $('#shell').sortable({cursor: 'move'});
});

Also the jsFiddle for easier understanding.

Thanks in advance for any advice.

1条回答
Viruses.
2楼-- · 2019-08-14 06:18

Here you go: http://jsfiddle.net/lotusgodkk/gtFMD/2/

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;
}

For array comparison: How to compare arrays in JavaScript?

查看更多
登录 后发表回答