encodeURI函数不对括号“()”进行编码

时间:2019-03-22 08:55:56

标签: jquery css

我正在尝试使用下面提到的js代码加载背景图片:

$('.main-banner').css('background-image', "url("+encodeURI(element.image)+")");

不幸的是,如果图像名称element.image包含括号:(),这将导致问题,并且图像将无法加载。

1 个答案:

答案 0 :(得分:1)

encodeURI将不会对括号进行编码,请尝试像这样手动替换它们:

const url = element.image.replace("(", "%28").replace(")", "%29");
$('.main-banner').css('background-image', "url("+encodeURI(url)+")");

在替换之前使用encodeURI方法就像:

const url = encodeURI(element.image).replace("(", "%28").replace(")", "%29");
$('.main-banner').css('background-image', "url("+url+")");