简体   繁体   中英

set variable to a variable that already exists based on name of variable

Lets assume, when the page is rendered i have a variable that looks like:

var test1 = 'this is a string of html'

I have a function that looks like :

  function addRow(v) {
    $.each(v, function (k,v) {
      if (k == 'jsvar') {
        cableHTML = 'test1'
        insertCabling(parentId, cableHTML)
      }
    });
  }

the variable that cableHTML is set to is dependent on jsvar 's value. So it will change depending on whats selected.

test1 might be test2 , or something else. test1/test2/test3 etc, all exist as variables on the page when its loads. the value pair of jsvar dictates what variable cableHTML needs to be.

I want to set cableHTML to the test variables that were loaded earler. Is there (hopefully) a simple way to accomplish this?

Based on what you said "the value pair of jsvar dictates what variable cableHTML needs to be", assuming that value is test1 , test2 , etc. You could do this:

  function addRow(v) {
    $.each(v, function (k,v) {
      if (k == 'jsvar') {
        cableHTML = eval("v");
        insertCabling(parentId, cableHTML)
      }
    });
  }

But you would be better off using an array ( eval() and indexed variable names are something you should always try to avoid), and doing something like:

  function addRow(v) {
    $.each(v, function (k,v) {
      if (k == 'jsvar') {
        cableHTML = myArray[v];
        insertCabling(parentId, cableHTML)
      }
    });
  }

Where the value for jsvar is the key for the item you want in your myArray array.

Also, if you aren't declaring var cableHTML somewhere else in this scope, you are making it a global var. As you are passing it as a parameter to insertCabling() I assume you don't want/need a global and you should just add var to cableHTML = ...


Also after looking at your code more, it seems the each() is unnecessary:

  function addRow(row) {
    if(row["jsvar"]){
      insertCabling(parentId, row["jsvar"]);
    }
  }

You need to get rid of the quotes around test1 and jsvar in your code, unless you want k to be equal to the string 'jsvar' and you want cableHTML to be equal to 'test' .

var test1 = 'this is a string of html';

function addRow(v) {
  $.each(v, function(k,v) {
    if (k == jsvar) {
      cableHTML = test1
      insertCabling(parentId, cableHTML)
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM