Chris
Chris

Reputation: 113

Avoiding multiple load functions in jquery

I have a 50-item ul. Is there a way to write to not have to write 50 of the below?

$(function(){
$("#nav_a").on("click", function(){
    $("#main_text").load("pageA.html #main_text");  
});
$("#nav_b").on("click", function(){
    $("#main_text").load("pageB.html #main_text");  
});    
$("#nav_c").on("click", function(){
    $("#main_text").load("pageC.html #main_text");  
});

Upvotes: 1

Views: 39

Answers (3)

WeiYuan
WeiYuan

Reputation: 5992

You can use the each() and eq() function built in jQuery. See example:

Html:

<ul>
  <li>0</li>
</ul>

<ul>
  <li>1</li>
</ul>

Javascript:

var color = ['red', 'blue'];

$("ul").each(function(i) {
  $("ul:eq( " + i + " )").css("color", color[i]);
});

And change it for your situation as below:

var page = ['pageA.html', 'pageB.html', 'pageC.html'];

$("#nav ul").each(function(i) {
    $("ul:eq( " + i + " )").on( "click", function() {
      $("#main_text").load(page[i] + " #main_text");  
    });
});

Upvotes: 0

BenG
BenG

Reputation: 15164

Use the starts-with selector ^= and split on the id to get the letter:-

$(function() {
  $('[id^="nav_"]').on("click", function() {
    var letter = this.id.split('_')[1];
    $("#main_text").load("page" + letter + ".html #main_text");
  });
});

if you want to keep the upper-case then + letter.toUpperCase() +

Upvotes: 2

kapantzak
kapantzak

Reputation: 11750

You can put a common class accross all of these elements like this:

<ul class="myElem" data-page="n">...

and in jQuery:

$(document).on('click', '.myElem', function() {
  var page = $(this).attr('data-page');  //Get the page
  $('#main_text').load('page' + page + '.html #main_text');
});

Upvotes: 1

Related Questions