Jquery - 用字符串获取变量

时间:2015-06-18 11:45:11

标签: jquery

我需要使用字符串访问变量。致电preSort时,最后一个参数为"l"。我需要使用“l”在l之后立即将preSort变量发送到t

预先分类(T,l(this var),P,N,Y,C,CO,S,搜索,标签,元素,"l(using this string)");

function preSort(t,l,p,n,y,c,co,s,search,tag,element,ident) {
    //var ident = getParameterByName(''+ident+'');
    toHtml = window[ident]; //this is blank
    if(toSort(t,l,p,n,y,c,co,s,search,tag) != false)
    {
        urlBuilder(t,l,p,n,y,c,co,s,search,tag)

    $(".refresh-"+element+"").remove();
    $("#sort-filter-"+element+"").append('<button id="'+ident+'" class="refresh refresh-'+element+' align-left btn btn-primary btn-sm">'+toHtml+' <i class="fa fa-times right"></i></button>');

    }
}

        $("#letter").change(function() {
        var t = getTab();
        var l = $(this).find('option:selected').val();
        var s = getParameterByName('s');
        var y = getParameterByName('y');
        var p = getParameterByName('p');
        var n = getParameterByName('n');
        var c = getParameterByName('c');
        var co = getParameterByName('co');
        var search = getParameterByName('q');
        var tag = getParameterByName('tag');

        $("#"+t).empty();
        var element = $(this).attr("id");

        preSort(t,l,p,n,y,c,co,s,search,tag,element,"l");
    /*
        if(toSort(t,l,p,n,y,c,co,s,search,tag) != false)
        {
            urlBuilder(t,l,p,n,y,c,co,s,search,tag)

            $(".refresh-letter").remove();
            $("#sort-filter-letter").append('<button id="l" class="refresh refresh-letter align-left btn btn-primary btn-sm">'+l+' <i class="fa fa-times right"></i></button>');
        }
    */
    });

2 个答案:

答案 0 :(得分:0)

  

我需要使用字符串

访问变量

您可以通过名称点符号括号访问变量(因为变量将是当前对象/函数的属性) ,在顶层窗口对象)。

var helloVar = "hello";
// get by variable name
var a = helloVar;
// get by dot notation
var b = this.helloVar;
// get by brackets passing a string within ""
var c = this["helloVar"]; <-- this one may help you

a,b,c都访问相同的变量值

答案 1 :(得分:0)

聊天摘要: 更具体的问题:

如何访问函数中的变量,该变量应引用函数头中的定义

function f(a,b,c,d,e,f,ident){
    var value = this[ident];  // this[ident] is undefined, no access to variable name
     alert(value);
}

f(111,222,333,4,5,6, 'c'); // should alert param 'c' = 333 --> undefined
f(111,222,333,4,5,6, 'c'); // should alert param 'f' = 6 --> undefined

我不知道通过变量名访问参数的方法。

解决方法: 而不是字母/变量名称,在函数调用中传递参数的索引。

function f(a,b,c,d,e,f,position){
    var value = arguments[position - 1];  //  -1 as array start with index 0
     alert(value);
}

f(111,222,333,4,5,6, 3); // should alert 3rd param = 333 --> ok
f(111,222,333,4,5,6, 6); // should alert 6th param = 6 --> ok