jQuery constants as variables for calling functions

只愿长相守 提交于 2021-02-19 01:32:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!