A better, cleaner way to write this jQuery code

I have written this currently, but the title says there is a better way to write / optimize this code?

var p = $('#pstrip');

$('a.Btn1').click(function() {
    p.animate({left: '0px'});
});
$('a.Btn2').click(function() {
    p.animate({left: '-730px'});
});
$('a.Btn3').click(function() {
    p.animate({left: '-1460px'});
});
$('a.Btn4').click(function() {
    p.animate({left: '-2190px'});
});
$('a.Btn5').click(function() {
    p.animate({left: '-2920px'});
});
+3
source share
4 answers

If all you want to do is cut it, something like this might work.

$.each([1,2,3,4,5], function(idx, el) {
    var ix = idx;
    $('a.Btn' + el).click(function() {
        p.animate({left: (-730*ix) + 'px'});
    });
})

EDIT . Unfortunately, the parameters were inverse.
EDIT 2 . As shown below, we need to make sure that he is calling correctly - I just acted differently.

+4
source
var p = $('#pstrip');
var coords = [0, -730, -1460, -2190, -2920];

for (var i = 0; i < 5; i++)
    $('a.Btn' + (i + 1)).click((function(index) {
        return function() {
            p.animate({left: coords[index]});
        }
    })(i));

a.Btn, (i + 1) - i- . , click, , , . ,

.click(function() { p.animate({left: coords[i]}); })

i , 5.

+2

, .click():

$("#button_container a").click(function() {
    $("#pstrip").animate({left: ($(this).attr("class").match(/Btn([0-9]+)/)[1] * -730) + "px"});
});

, javascript.

+2

, , Btn. , #pstrip .

$("a[class^=Btn]").on("click", function(){
  var n = -730 * ( this.className.match(/\d+/) - 1 );
  $("#pstrip").animate({ left: n + 'px' });
});

.

Demo: http://jsbin.com/ovibun/5/edit
Performance: http://jsperf.com/five-buttons/3

enter image description here

+2
source

All Articles