我有一个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));

10-04 22:46
查看更多