我有以下代码:
$.each(css, function(i, v) {
css[i] = this.replace('{bind}', bindName, css[i]);
});
我想用 bindName 的值替换所有 {bind}。 为了尝试这个,我给了 bindName 值“Test”。
'css' 是一个带有数据的简单对象。
var css = {
tabs : 'tab-{bind}',
outerWrapper : 'outerWrapper-{bind}',
innerWrapper : 'innerWrapper-{bind}-{id}-{tab}',
subMenue : 'subMenue-{bind}-{id}',
subMenueItem : 'subMenue-Item'
};
在 Firefox 中,我在第 68 行收到错误“无效的正则表达式标志 k”。 第 68 行:
$.each(css, function(i, v) {
css[i] = this.replace('{bind}', bindName, css[i]); // LINE 68
});
如果有必要,这是我的替换功能:
this.replace = function (s, r, su) {
return su.split(s).join(r);
}
在 Google-Chrome 中没有错误,但在 Firefox(最新版本)中没有错误 - 你能找到错误吗?
最佳答案
改变这个:
css[i] = this.replace('{bind}', bindName, css[i]);
任何一个:
css[i] = this.replace('{bind}', bindName);
css[i] = v.replace('{bind}', bindName);
css[i] = css[i].replace('{bind}', bindName);
错误消息的原因是在 Firefox 中,String.replace
采用可选的第三个参数来表示正则表达式标志(例如 'i'
或 ' g'
);您正在为该参数传递 css[i]
,而 Firefox 将其解释为包含无效标志。 Chrome 不给出错误消息的原因是它不支持该非标准功能,因此它完全忽略了该参数。
关于javascript无效的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9791108/