jQuery常量作为调用函数的变量 [英] jQuery constants as variables for calling functions

查看:61
本文介绍了jQuery常量作为调用函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中,是否可以将变量作为常量?我知道在许多其他语言中是不可能的,但是jQuery从未使我感到惊讶.无论如何,也许这不是正确的问题,我正在尝试使用循环索引作为ID,其中ID调用方法.通过每个循环,ID都会发生变化,而我试图从一组不同的 a 元素中触发相同的功能.如何更改代码以具有动态调用方?

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
      }

   }

推荐答案

jQuery 是javascript库,它不是语言,并且没有常量.您只能创建一个虚数常量,该常量与变量不同.

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.

例如:

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
     }
 }

这篇关于jQuery常量作为调用函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆