How to convert a string value to a variable in javascript?

前端 未结 5 619
[愿得一人]
[愿得一人] 2021-01-27 09:46
var test1;
$(document).ready(function () {
    test1 = $(\"#test1ID\").jQueryPlugin();
});

var test2;
$(document).ready(function () {
    test2 = $(\"#test2ID\").jQuery         


        
相关标签:
5条回答
  • 2021-01-27 10:04

    It might be worth creating an object to hold all your "tests":

    var tests = {};
    
    $(document).ready(function () {
        tests.test1 = $("#test1ID").jQueryPlugin();
        tests.test2 = $("#test2ID").jQueryPlugin();
    });
    
    for(i=0; i < theArrayOfStrings.length; i++){
        tests[theArrayOfStrings[i]].foo();
    }
    
    0 讨论(0)
  • 2021-01-27 10:04

    Have you tried

    $('#' + theArrayOfStrings[i]).foo();
    

    Have a look at API/1.3/Selectors

    0 讨论(0)
  • 2021-01-27 10:05

    If test1 is a global variable you can access it by name through the window object:

    window[theArrayOfStrings[0]].foo();   // test1();
    

    If it's not, eval is the only way, but I'd strongly advise avoiding eval in all circumstances. Using a lookup as in J-P's answer (+1) is much much more appropriate than selecting variable names.

    0 讨论(0)
  • 2021-01-27 10:14

    eval() function is used to evaluate script in a string variable. For example :

    var test1;
    eval("test1=" + theArrayOfStrings[i]);
    test1.foo();
    

    But take a lok at this question before use When is JavaScript’s eval() not evil?

    0 讨论(0)
  • 2021-01-27 10:16
    var test = [], n = 5;
    $(document).ready(function () {
        for(var i=0; i < n; i++)
            test.push($("#test"+i+"ID").jQueryPlugin());
    });
    
    // the values in test won't be accessible before the document is loaded.
    
    0 讨论(0)
提交回复
热议问题