jQuery: verificare l'uguaglianza dei selettori

jQuery: verificare l'uguaglianza dei selettori

jQuery non dispone di un metodo per comparare i selettori e per verificarne l'uguaglianza. Tuttavia, grazie alla possibilità offerta da jQuery di aggiungere metodi alla libreria tramite plugin, possiamo facilmente ovviare a questa situazione. Vediamo come.

Creiamo il seguente plugin:


(function($) {

    $.fn.isEqual = function($otherSet) {
        if (this === $otherSet) {
            return true;
        }
        if (this.length != $otherSet.length) {
            return false;
        }
        var ret = true;
        this.each(function(idx) {
            if (this !== $otherSet[idx]) {
                ret = false;
                return false;
            }
        });
        return ret;
    };

})(jQuery);

Faremo un test con la seguente struttura HTML:


<div class="test">Test</div>
<p id="test">Test</p>

Ecco il nostro test:


$('#run').click(function() {

    var $test1 = $('div.test').eq(0);
    var $test2 = $('#test');

    var test1 = ($test1.isEqual($test1)) ? ' is equal to ' : ' is not equal to ';
    var test2 = ($test1.isEqual($test2)) ? ' is equal to ' : ' is not equal to ';

    $('#results').html('div.test ' + test1 + 'div.test' + '<br/>' + 'div.test' + test2 + 'p#test');


    return false;

});

Potete visionare l'esempio finale in questa pagina.

Torna su