jquery session - 动态变量命名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/556350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery session - dynamic variable naming
提问by mars-o
just having a problem here.
i'm doing the UI of a web-based app using jquery, css.
there's a shopping a cart, and i want to store the selected items in the session, i used jquery.session plugin.
e.g. var $.session("var1","item1");
只是这里有问题。我正在使用 jquery、css 制作基于 Web 的应用程序的 UI。有一个购物车,我想在会话中存储选定的项目,我使用了 jquery.session 插件。例如var $.session("var1","item1");
What i want is to dynamically store items into dynamically named variables. how could i do that?
我想要的是将项目动态存储到动态命名的变量中。我怎么能那样做?
thanks.
谢谢。
回答by
If there's a shopping cart, that data should be handled by a server side scripting language like PHP. I'm assuming at the end they will be charged via credit card? This kind of data needs to be secure.
如果有购物车,则该数据应由服务器端脚本语言(如 PHP)处理。我假设最后他们会通过信用卡收费?这种数据需要安全。
In addition, that's a pretty big part of functionality to be handled by a non-secure client-side language like JS that can be turned off.
此外,这是由非安全客户端语言(如可以关闭的 JS)处理的功能的很大一部分。
Just something to think about in the future..
只是将来要考虑的事情..
回答by jonstjohn
One way that you could do that is to create a function that stores the 'session' variables. The session would have two parameters, the variable name and its value. For example:
您可以这样做的一种方法是创建一个存储“会话”变量的函数。会话将有两个参数,变量名和它的值。例如:
function setSession(name, value) {
$.session(name, value);
}
Whenever you need to set the jQuery session variable, just call the function as in:
每当您需要设置 jQuery 会话变量时,只需调用该函数,如下所示:
setSession('var1', item1);
回答by jonstjohn
Just use strings to build it up to what you want, like so:
只需使用字符串将其构建为您想要的,如下所示:
function storeValueInCart(cartId, value) {
$.session("var"+cartId, value);
}
You can also store arbitrary data on elements and use them, like so:
您还可以在元素上存储任意数据并使用它们,如下所示:
$(".vote_action").each(function() {
vote_id = $(this).attr("id").substring("action_".length);
$(this).data("vote_id", vote_id);
});
以上循环通过设置了 vote_action 类的每个元素。在它发现的每个元素上,它都获得了 id 属性,它是一个类似 action_NN 的字符串,然后砍掉动作部分。然后它将这个vote_id 作为任意数据存储在“vote_id”名称下的元素上。回答by svinto
Since the session function takes strings as parameters, just create these strings dynamically.
由于会话函数将字符串作为参数,因此只需动态创建这些字符串即可。