获取与字符串值同名的变量的值
Get the value of a variable with with the same name as the value of a string
我有一个jQuery小部件,它在调用时输出目录。
我想让用户有机会在内容中指定每个独立元素的 ID(默认情况下listElementID: 'contents-{index}'
(,所以我在小部件中想出了一个函数来实现这一点。
这方面的标准很简单——
- 将
{index}
替换为传递给函数的index
参数的值。 - 替换和
{.*}
的其他实例(即{whatever}
匹配的小部件选项this.options.whatever
。
我可以从this.options.listElementID
中提取所需的变量,但我似乎找不到一种方法来获取匹配参数/选项的值。
我尝试使用 eval()
来做到这一点(对不起!(,但如果例如 varName = 'index';
,eval('varName');
只返回索引,而不是 index
参数的值。
如何更正我的代码?
_getContnetsLineID : function(index){
var vars = (this.options.listElementID.match(/{.*}/g) || []),
ID = this.options.listElementID;
for(var i = 0; i < vars.length; i++){
var varName, // The name of the variable to grab the value from
value; // The value to replace the placehoder with
varName = vars[i].replace('{', '').replace('}', ''); // Remove the '{' and '}' characters from the 'varName'
if(varName == 'index'){ // Attempt to grab the value from a variable that matches the string 'varName'
value = eval('varName');
} else {
value = eval('this.options.varName');
}
ID = ID.replace(vars[i], value); // Replace the placeholder with the appropriate value
}
return ID;
} // _getContnetsLineID
考虑:
this.options = {
listElementID: "foobar-{index}-{whatever}",
whatever: "hi"
};
_getLineID = function (index) {
return this.options.listElementID.replace(/{(.+?)}/g, function (_, name) {
return name === 'index' ? index : this.options[name];
});
}
document.write(_getLineID(25));
相关文章:
- 从javascript变量获取php会话
- 是否将Javascript变量保存为PHP变量?获取、发布、COOKIE
- 从动态变量获取数组
- PHP 和 Javascript:使用 Javascript 变量获取文件内容
- 如何从 php 变量获取值到我们的 javascript 文件中
- 从 javascript 变量获取 InnerHtml
- 如何使用此变量获取 typeahead.js 中输入的 id
- 使用参数变量获取传递给 ES6 箭头函数的参数
- 如何将此值作为变量获取
- Javascript-使用一个变量获取数组的一部分
- 无法使用AJAX将JS变量获取到PHP
- 从angularjs中的变量获取数据
- 使用jquery中的变量获取字段值
- 将变量获取到url并导航选定的变量
- 将Struts2 valuestack变量获取到JQuery
- Javascript-使用变量获取对象值
- 为每个变量获取一个新的随机数
- 从JavaScript中的第二个变量获取名为的变量的值
- 使用变量获取 JavaScript 值
- HTML选择列表-通过传递变量获取文本值