问题
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
}
}
回答1:
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
}
}
来源:https://stackoverflow.com/questions/21073156/jquery-constants-as-variables-for-calling-functions