jquery 从 href 值设置 css 背景

标签 jquery css background anchor

我有一个图像路径正在输出到 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/

相关文章:

javascript - Selectize.js - 添加项目时执行某些操作

html - 删除 CSS 按钮轮廓

css - 居中的 DIV,两边有不同的背景

Java SWT - 缩放背景图像在编译后不起作用

javascript - jQuery 导出的文件在 Excel 中打开时显示错误

php - 根据所选付款方式启用/禁用 WooCommerce 所需的结帐字段

html - 两个div的高度基于主div的高度相等

html - 无论屏幕尺寸如何,创建适合父级的图像

javascript - 使用 Jquery 删除原始文本

javascript - 我如何制作这样的菜单?