我确实尝试这样做(使用 jQuery):
type = (blabla == blublu)? 'category':'regular';
(type+'Name').val('...');
这是控制台响应:
Uncaught TypeError: Object categoryName has no method 'val'
虽然它们确实存在...
那么我怎样才能让它发挥作用呢??
编辑:
这是完整的功能:
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);});
}
我尝试 (type+'Name') 创建对现有 var 或对象的引用。
最佳答案
您的问题不在于串联。那很好用。您将 type
与 'Name'
连接起来,得到字符串 'categoryName'
。然后你这样做:
('categoryName').val(...);
这与 'categoryName'.val(...)
相同,这显然行不通,因为字符串没有 val
方法。
您正在尝试进行 jQuery 选择,为此您需要 jQuery 构造函数:
$(type+'Name').val('...');
当然,这也不太可能奏效,除非您有标签名称为 categoryName
的元素。大概您实际上想要具有该类的元素:
$('.' + type + 'Name')
或id
:
$('#' + type + 'Name')
或类似的东西。
关于javascript - JavaScript中有没有一种方法可以将字符串+变量用作变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19768149/