1

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");  
});
0

3 Answers 3

2

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() +

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'm going to have to look into split -- seems like something I should learn next.
1

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

1 Comment

I'm not sure how to get this one to work. Do I need to do something with the data-page="n"? I've got code that looks like this: <li><a id="nav_a" href="#">"I Have Already Told You Everything"</a></li> <li><a id="nav_b" href="#">A Bit of the Old Nick</a></li> <li><a id="nav_c" href="#">A Decade of Christmas</a></li>
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.