【问题标题】:Why does jQuery(this).css('background-image') return the browser URL? [closed]为什么 jQuery(this).css('background-image') 返回浏览器 URL? [关闭]
【发布时间】:2012-11-02 19:02:47
【问题描述】:

我有三个 div,如下所示。

<div id="div#product_img_wrapper">
    <div id="product_design1" class="timage"  style="z-index: 20; background-image: url('');"></div>
    <div id="product_design2" class="timage"  style="z-index: 20; background-image: url('');"></div>
    <div id="product_design3" class="timage"  style="z-index: 20; background-image: url('');"></div>
</div>

我使用下面的 jquery 函数在 div 上方循环槽,如下所示。

jQuery('div#product_img_wrapper div').each(function(){

            var background = jQuery(this).css('background-image').replace('url(','').replace(')','');

            if(background != 'none')
            {
                console.log(jQuery(this));
                console.log(background);
            } 


        });

输出

"http://localhost/project/index.php?option=com_project&controller=project&task=project&method=1"
"http://localhost/project/index.php?option=com_project&controller=project&task=project&method=1"
"http://localhost/project/index.php?option=com_project&controller=project&task=project&method=1"

我想要做的是获取每个 div 的 background-image 属性。但它返回我这个浏览器显示的 URL?上面的代码有什么问题?为什么 jQuery(this).css('background-image') 返回浏览器 URL?

【问题讨论】:

  • 您是否尝试过设置背景图片 URL?它在您的代码中看起来是空白的
  • 为什么你的 id 属性中会有div#?这肯定会混淆 jQuery 选择器引擎

标签: javascript jquery html css foreach


【解决方案1】:

url('') 是解析为“此处”的相对 URL。

您正在获取您指定的 URL,只是解析为绝对形式,而不是您输入的原始相对形式。

【讨论】:

    【解决方案2】:

    URL 是相对的,并且设置为绝对的。

    你应该写这个来获得背景:

    var background = jQuery(this).css('background-image').replace('url(' + location.href,'').replace(')','');
    

    【讨论】:

    • 我的错,我写的是this.href而不是location.href
    • 还是一样。不过还是谢谢。我想通了
    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2013-01-06
    • 2017-03-04
    • 2021-07-27
    • 2017-07-08
    • 2013-01-04
    相关资源
    最近更新 更多