Jim22150
Jim22150

Reputation: 511

jQuery constants as variables for calling functions

In jQuery, is it possible to have a variable as a constant? I know it is not possible in many other languages, but jQuery never ceases to surprise me. Maybe this isn't the right question, anyway, I am trying to use a loop index as an ID, of which the ID calls a method. Through each loop the ID changes and I'm trying to trigger the same function from a set of different a elements. How can I change my code to have a dynamic caller?

  for(var i in data.items) {

      var id = $(i);
      var viewMore = $("<a href=# id=" + id + ">View More</a>");

      id.on('click', function(x) { 
          // do something
      }

   }

Upvotes: 5

Views: 22252

Answers (1)

Dmitriy.Net
Dmitriy.Net

Reputation: 1500

jQuery is javascript library, It is not language, and it doesn't have constants. You can only create an imaginary constant, which will differ from variables.

For example:

var MY_CONSTANT = "my constant value";

As for your sript, as for me, the more correct way is:

 // It is your constant
 var VIEW_MORE = $("<a href='#'>View More</a>");

 for(var i in data.items) 
 {
     VIEW_MORE.clone().attr('id', i).on('click', function(x) 
     { 
           // do something
     }
 }

Upvotes: 8

Related Questions