简体   繁体   中英

is there a way in JavaScript to use string+variable as a variable

I did try to do this (with jQuery):

type = (blabla == blublu)? 'category':'regular';
(type+'Name').val('...');

this is the console response:

Uncaught TypeError: Object categoryName has no method 'val'

although they actually exist...

so how can I make it work??

edit:

this is the full function:

var type = (1 == 1)?'something':'blabla';

var somethingName = $('#somethingName');
var blablaName = $('#blablaName');
more variables like this..

function itemMode(mode, inputValue){
  inputValue = (typeof inputValue !== 'undefined')? inputValue:'';
  var functionName = null;
  switch(mode){
  case 'open':
    btnValue = 'something';
    functionName = editCategory; // this need to be from type to
    openItem = true;
    break;
  case 'close':
    btnValue = 'something';
    functionName = addCategory; // this need to be from type to
    openItem = false;
    break;
  default:
    return false;
  }
  (type+'Name').val(inputValue);
  $('#btn'+type.capitalize()).off('click').val(btnValue).click(functionName);
  (type+'Name').off('keypress').keypress(function(e){enterPress(e,functionName);});
}

i try (type+'Name') to crate reference to an existing var or object.

Your problem is not with the concatenation. That works fine. You concatenate type with 'Name' , and you get the string 'categoryName' . You then do this:

('categoryName').val(...);

This is the same as 'categoryName'.val(...) , which obviously won't work, because strings do not have a val method.

You are attempting to do a jQuery selection, for which you need the jQuery constructor:

$(type+'Name').val('...');

This, of course, is also unlikely to work, unless you have elements with the tag name categoryName . Presumably you actually want elements with that class:

$('.' + type + 'Name')

or id :

$('#' + type + 'Name')

or something similar.

Variables are created as properties of the window object, so if they are global you can do this...

window[type + "Name"]

Since you want to refer to a "cached" jQuery object, use the following...

(window[type + "Name"]).val("123");

For example, if you've cached a jQuery object like this...

var sumVar = $('#sumid');

You can refer to it directly like this...

sumVar.val("123");

Or you can refer to it using a variable as the name, like this...

var varName = "sumVar";

(window[varName]).val("123");

Here's a modified version of the script you posted above...

var type = (1 == 1)?'something':'blabla';

window.somethingName = $('#somethingName');
window.blablaName = $('#blablaName');

function itemMode(mode, inputValue){
    inputValue = (typeof inputValue !== 'undefined')? inputValue:'';
    var functionName = null;
    switch(mode){
        case 'open':
            btnValue = 'something';
            functionName = editCategory; // this need to be from type to
            openItem = true;
            break;
        case 'close':
            btnValue = 'something';
            functionName = addCategory; // this need to be from type to
            openItem = false;
            break;
        default:
            return false;
    }

    (window[type + 'Name']).val(inputValue);

    $('#btn' + type.capitalize()).off('click').val(btnValue).click(functionName);

    (window[type + 'Name']).off('keypress').keypress(function(e){enterPress(e,functionName);});
}

You can create a function and use it's returned value:

DEMO1 DEMO2

function type(){
  return (blabla == blublu) ? 'category' : 'regular';
}


$('[name="'+ type() +'Name"]').val('SOME VALUE'); 

If you use ID rather than name attribute:

function type(){
  return (blabla == blublu) ? '#category' : '#regular';
}


$( type() +'Name').val('SOME VALUE'); 

Or just simply:

var typeID =  blabla==blublu? '#category' : '#regular';
$( typeID +'Name').val('SOME VALUE'); 

val() is a method provided by jquery. So to access it you will need to use the '$' operator along with the mode of selection :

var type = (blabla == blublu)? 'category':'regular';

For accessing using : 进行访问:

$("#"+type).val("...");

For accessing using : 访问:

$("."+type).val("...");

For accessing using any custom attribute for eg. :

$("data['"+type+"']").val("...");

You only can safely do that with an object key.

Create an object like so.

var obj = {
   'categoryName': ...

};

To retrieve it use something like this:

obj[someString]

eval is an option is not wise.

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