5

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
      }

   }
3
  • 1
    may be for (var i in data.items) { var id = $(i); var viewMore = $("<a href=# id=" + o + ">View More</a>"); viewMore.on('click', function (x) { // do something }) } Commented Jan 12, 2014 at 9:34
  • Hm no @arun, I can't think of the best way to ask the question. I'm trying to call an ID of an element to trigger the function, not call with the entire element via string. Commented Jan 12, 2014 at 9:40
  • @arun, your code works, it was actually my original, but now I am trying to shrink my code; and my question seems like there is an answer. Commented Jan 12, 2014 at 9:50

1 Answer 1

8

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
     }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

I'm know my question is not politically worded correctly, but would you say there is a way for me to call the click method with an id that changes after every loop?
Very nice @Dmitriy.Net! I didn't think about the clone function; that's exactly what I needed. Thanks!

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.