jquery session - dynamic variable naming

半城伤御伤魂 提交于 2019-12-22 00:07:03

问题


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");

What i want is to dynamically store items into dynamically named variables. how could i do that?

thanks.


回答1:


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.

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.

Just something to think about in the future..




回答2:


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:

setSession('var1', item1);



回答3:


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);
    });
The above loops through each element with the vote_action class set. On each element it finds it gets the id attribute, which is a string like action_NN, and then chops off the action part. Then it stores this vote_id as arbitrary data on the element under the "vote_id" name.




回答4:


Since the session function takes strings as parameters, just create these strings dynamically.



来源:https://stackoverflow.com/questions/556350/jquery-session-dynamic-variable-naming

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