Domanda

how to shorten the code? He wants to apply the principle of DRY? Here code:

$('a[href^="#register"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load('register.html');
    e.preventDefault();
});

$('a[href^="#blog"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load('blog.html');
    e.preventDefault();
});

$('a[href^="#contact"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load('contact.html');
    e.preventDefault();
});

Please help :)

È stato utile?

Soluzione 2

apply class on anchor tags and write event on class like this:

$('a.MyClass').click(function(e){


$('.box').addClass('active');
$('.box div').load($(this).attr("href").split('#')[1]+'.html');
e.preventDefault();


});

Altri suggerimenti

Try something like:

$('a[href^="#register"], a[href^="#blog"], a[href^="#contact"]').click(function(e){
    $('.box').addClass('active');
    $('.box div').load(this.getAttribute('href').split('#')[1]+'.html');
    e.preventDefault();
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top