0

我期待这能奏效

var url = 'http://path_to_some_image.jpg';
$('body').css('background-image', "url('" + encodeURIComponent(url) + "')");

但我得到 404 not found 错误。浏览器无法处理 css 中编码的 url 是否有原因?

如果我使用原始 url 它可以工作,但如果 url 包含引号和东西怎么办?我必须使用正则表达式手动替换它们:/

4

1 回答 1

2

You should do encodeURI

var url = 'http://path_to_some_image.jpg';
$('body').css('background-image', "url('" + encodeURI(url) + "')");

The difference is

encodeURI assumes that the input is a complete URI that might have some characters which need encoding in it.

encodeURIComponent will encode everything with special meaning, so you use it for components of URIs such as

于 2015-03-12T18:14:35.317 回答