1

几天前我写了一个简单的东西,如果无法加载所需的图像,则回退到占位符图像。它允许用户使用 2 个占位符来定义图像大小:

就是我写的东西

;(window.jQuery || window.Zepto).fn.fallback = function (url) {
    return this.one('error', function () {
        this.src = (url|| 'http://lorempixel.com/$w/$h')
        .replace('$w', this.width).replace('$h', this.height);
    });
};

我现在问我,是否可以.replace('$w', this.width).replace('$h', this.height);用更短但等于regex将所有$*(美元+第一个字符)替换为任何对象的赋值?

像这样的东西:

'$f is not equal to $b'.replace(/magicregex/, {
    foo: 'foo',
    bar: 'bar'
});

这样我们就可以使用所有properties来自image-object, 例如image.width, image.src, image.width...

4

1 回答 1

1

仅当您使用函数作为替换时。喜欢:

"$w/$h".replace(/\$[wh]/g, function(m){ return m == "$w" ? width : height; });

您也可以取消这样的比较:

"$w/$h".replace(/\$(?:(w)|h)/g, function(m, w){ return w ? width : height; });

如果要在哈希中查找值,可以使用:

"$w/$h".replace(/\$(\w+)/g, function(m, name){ return hash[name]; });
于 2013-07-01T10:32:57.583 回答