【问题标题】:use variable inside src attribute with jquery在 jquery 的 src 属性中使用变量
【发布时间】:2015-04-18 13:35:00
【问题描述】:

我在网站项目上使用 B-Lazy 插件 (http://dinbror.dk/blog/blazy/)。我想根据窗口宽度加载不同的图像:

如果窗口宽度

所以,我想获取 data-src 图像 url 并在 '.jpg' 之前添加到末尾的 '-228x170' :

<img data-src="img-name.jpg" > 变得 <img data-src-small="img-name-228x170.jpg" >

这里是我的代码: `

$('img').addClass('b-lazy');

$("img.b-lazy").each(function() {       

         $(this).attr("data-src",$(this).attr("src"));
         $(this).attr('src','data:trans.gif');

        var src = $(this).attr('data-src');
        $(this).attr('src', 'src + -228x170.jpg' ); //here my mistake

 });

`

【问题讨论】:

    标签: jquery image attributes src jquery-lazyload


    【解决方案1】:

    给你,只需更改引用的位置,并删除初始扩展名:

    var src = $(this).attr('data-src').replace('.jpg', '');
    $(this).attr('src', src + '-228x170.jpg' );
    

    cmets 中的每个问题:

    var src = $(this).attr('data-src').replace('.jpg', '');
    var specialChars = ('fooo'); //this can be set dynamically
    
    $(this).attr('src', src + '-228' + specialChars  + '.jpg' );
    

    HTH, -泰德

    【讨论】:

    • 而且,如果我不想指定高度值 'x170' ?是否可以写类似(this).attr('src', src + '-228????.jpg' );.jpg 之前未指定四个字符的内容?
    • 因为它是一个字符串,你可以放任何你需要的东西,
    • 谢谢@Ted 但我不知道怎么写-228 + (4 caracters who are not always the same) + .jpg
    • 我在答案中添加了一个示例。这就是你的想法吗?
    • 是的,谢谢你的例子。事实上,我想动态替换('fooo'),你说的是“4 个字符”,在不同的情况下会发生变化。例如:src + -228 + x356 + .jpgsrc + -228 + x657 + .jpg 或....等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2013-02-18
    • 2012-06-24
    • 1970-01-01
    • 2013-07-10
    • 2020-01-18
    • 2012-11-16
    相关资源
    最近更新 更多