我有一个图像路径正在输出到 anchor 标记的 href。我想将该图像设置为 anchor 的背景。
这是我的代码片段:
jQuery('.initialize a').css({
backgroundImage: 'url(' + this.href + ')'
,backgroundRepeat: 'no-repeat'
,backgroundPosition: '0 0'
});
返回背景图片:url(foo/undefined);在 anchor 上。
我做错了什么?
预计到达时间:
jQuery('.initialize a').each(function() {
this.setAttribute("href", this.getAttribute("href").replace(',\'', ''));
var href = this.getAttribute("href");
this.setAttribute("href", href.substr(0, href.length-14));
});
所以我使用上面的方法稍微清理了 href 属性的输出。
针对我的问题的建议解决方案:
$(this).css({background-image: 'url(' + this.href + ')', ...});
应该适合那里。但是我没有让它工作,大概是由于我的 jQuery 函数的格式化方式。我目前无法使用 $。我该如何适应它?
最佳答案
您可以使用 this
的 jQuery 对象来获取 href。
$(this).attr('href');
关于jquery 从 href 值设置 css 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9432105/