CSS和JQuery:空格内部图像名称破坏代码url() [英] CSS and JQuery: spaces inside image name break code of url()

查看:74
本文介绍了CSS和JQuery:空格内部图像名称破坏代码url()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,当滑过缩略图时,应显示较大版本的图片。

I have a page that is supposed to display a larger version of an image when hovered over a thumbnail.

我有一个带有ID的'div',JQuery代码如下:

I have a 'div' with an ID and the JQuery code is as following:

$(document).ready(function(){

  $('img').hover(function() {

    var src = $("#im" + this.id).attr("src");
    $('#viewlarge').css('backgroundImage','url(' + src +')'); 
    return false;
  });

});

我使用的图像是由Ruby脚本生成的,脚本生成但不同的id。然而,有时,照片上传有空格里面。我的开发人员工具告诉我,背景图片设置不正确,但图片路径正确,浏览器找不到图片没有问题。

The images I use, are generated by a Ruby script that "generate" an image with a similar, yet different id. However, sometimes, photo's are uploaded that have "spaces" inside. My developer tools tell me that the background-image is not set correctly, yet the image path is correct and the browser don't have problems finding the image.

我的问题是,我可以以某种方式清理urlsrc,所以空间不会是一个问题?我知道做这个服务器端,但我想知道如何做到这一点与JQuery / JS太。

My question is, can I somehow sanitize the url 'src', so spaces won't be a problem? I am aware of doing this server side, yet I would like to know how to do this with JQuery/JS too.

谢谢!

推荐答案

空格在URI中无效。它们需要编码为%20

Spaces are not valid in a URI. They need to be encoded to %20.

您可以 src.replace / g,'%20'),或更一般地, encodeURI(src) -encode在URI中无效的所有字符。 encodeURIComponent(src)更常见,但只有当 src 只是一个相对文件名时才有效;

You could src.replace(/ /g, '%20'), or more generally, encodeURI(src) to %-encode all characters that aren't valid in a URI. encodeURIComponent(src) is more common, but it would only work if the src was just a single relative filename; otherwise, it'd encode / and stop paths working.

但是,真正的问题 strong>是原来的 img src 已经打破,只有工作感谢浏览器修复更正您的错误。您需要修复生成页面的Ruby脚本。您应该在将文件包括在路径中之前对其进行URL编码;有更多的字符可以导致你的问题,而不仅仅是空格。

However, the real problem is that the original img src is already broken and only working thanks to browser fixups correcting your error. You need to fix the Ruby script generating the page. You should be URL-encoding the filename before including it in the path; there are many more characters that can cause you problems than just space.

正如Pekka所说,你还应该在 url (...)值。虽然您可以在没有许多网址的情况下离开,但有些字符必须 \ - 转义。使用双引号意味着你可以避免(在URL本身中不能出现双引号)。

As Pekka said, you should also use quotes around the URL in the url(...) value. Whilst you can get away without them for many URLs, some characters would have to be \-escaped. Using double-quotes mean you can avoid that (no double-quotes can appear in a URL itself).

这篇关于CSS和JQuery:空格内部图像名称破坏代码url()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆