开发者

error to change dynamically background url / image src

开发者 https://www.devze.com 2023-04-11 03:17 出处:网络
I am changing background:url(\'image-file\') or img\'s src dynamically and it\'s doing as i expected but one problem i am getting when the file has space between the name e.g. file name.gif (Not loadi

I am changing background:url('image-file') or img's src dynamically and it's doing as i expected but one problem i am getting when the file has space between the name e.g. file name.gif (Not loading) or file-name.gif (load successfully)

  var file-src = ../context/image file.jpg  /*not changing */
              /* ../context/image-file.jpg : changes   */

 if(this.is('img')){   /* 'this' is selecter */
    t开发者_运维技巧his.attr('src', file_src);
    }else{
    this.css('background','url('+ file_src +')');
    }

as far as i am not very sure why such files are not loading, i just try my best to find out the reason but i want to know if there could be any other reason.


You should cover filename by quote. Your code should be change to:

var file-src = '../context/image file.jpg';

this.css('background',"url('"+ file_src + "')");


URLs cannot have spaces in them. A space should be represented by a %20. You can use the encodeURI function to properly encode special characters.

Your javascript also doesn't look correct as strings must be quoted, but I'm assuming that's just a shortcut you took when posting.

0

精彩评论

暂无评论...
验证码 换一张
取 消