我有一个 jQuery 小部件,在调用时会输出目录。
我想让用户有机会指定内容中每个单独元素的 ID(默认为 listElementID: 'contents-{index}'
),因此我在小部件中提供了一个函数来实现此目的。
这个标准非常简单 -
- 替换
{index}
值为index
传递给函数的参数。 - 替换
{.*}
的其他实例(即{whatever}
以及匹配的小部件选项this.options.whatever
。
我可以从this.options.listElementID
中提取所需的变量,但我似乎找不到一种方法来获取匹配参数/选项的值。
我尝试使用eval()
来做到这一点(抱歉!),但如果例如 varName = 'index';
, eval('varName');
只是返回 index,而不是 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 - 获取与字符串值同名的变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35175528/