Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
      }

   }
like image 921
Jim22150 Avatar asked Jan 12 '14 09:01

Jim22150


People also ask

Can a const be a function?

A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended practice to make as many functions const as possible so that accidental changes to objects are avoided.

Should functions be const or let?

Summary. As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.

What does const {} mean in JavaScript?

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

How do you call a function inside a variable?

we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.


1 Answers

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
     }
 }
like image 58
Dmitriy.Net Avatar answered Oct 04 '22 21:10

Dmitriy.Net