Kyanite
Kyanite

Reputation: 756

Dynamically create numerous methods in jQuery?

A number is generated on my page in a hidden text field based on a number of 'pages' that need to be produced.

The plan is to dynamically allow the user to switch between the pages by clicking on numbers (e.g. if we have 3 pages, they can click on 1, 2 or 3 to display each page).

The problem is that the number of pages will vary from run to run, but in order for me to be able to add the page switching functionality in js/jQuery, I need to create a .click() method for each page button.

However because the number of pages isn't a set amount, I need to somehow create these methods dynamically - creating as many as are required, so a .click() function for each page.

$("#page1" ).click(function() { 
          for(var i = 0; i < tableCount; i++){
              $("#usertable" + (i)).hide();
          }

          $("#usertable1").show();
    });

Above is an example of a simple function I wrote that will be executed when the 1st page button is pressed and it iterates through all pages, hides them and then shows the 1st page. However if I have 5 pages, I need to somehow dynamically create a $("#page2" ).click() function and a $("#page3" ).click() function and so on.

Any ideas?

Upvotes: 0

Views: 38

Answers (2)

charlietfl
charlietfl

Reputation: 171690

Use of common classes and some attributes will help

<a class="page-link" href="#page1">Page 1</a>

<div id="page1" class="page-content"></div>

Then one click handler works for whole class of links. Within any jQuery event handler this is the element the event occured on

$('.page-link').click(function(){
     // hide whole class of content , filter for the one to show
     $('.page-content').hide().filter(this.hash).show();
});

Or a bit more verbose for understanding

$('.page-link').click(function(){         
     var idSelector = $(this).attr('href'); // "#page1"
     $('.page-content').hide().filter(idSelector).show();    
});

Upvotes: 2

guest271314
guest271314

Reputation: 1

You can use attribute begins with selector

$("[id^=page]").click(function () {
  // do stuff
  var id = this.id.slice(-1);
  for (var i = 0; i < tableCount; i++){
    $("#usertable" + i).not("[id$=" id "]").hide();
  }
  $("#usertable" + id).show();
})

Upvotes: 2

Related Questions