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
}
}
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.
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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With