将所有图像替换为元素自己的id + .jpg

时间:2014-07-30 11:37:01

标签: jquery

替换某些元素上的所有背景图片的好方法是,每个元素都有自己的ID +" .jpg"?使用jquery

我是否需要使用$ .each,或者我可以编辑它以某种方式工作:

$(".element").css("background-image", "url(img/" + $(this).data("id") + ".jpg)");
// it sets undefined.jpg, $(this) is not the way

编辑PS:数据(" id")不是拼写错误。我在元素上使用data.id

4 个答案:

答案 0 :(得分:5)

你可以使用.css()的setter版本获取function as the second argument,然后从该函数返回样式值

$(".element").css("background-image", function () {
    return "url(img/" + $(this).data("id") + ".jpg)"
});

在您的情况下,this将引用您编写代码的函数的上下文,而不是需要引用当前的.element元素。

答案 1 :(得分:0)

您可以使用每个()。

$( ".element" ).each(function( index ) {
    $(this).css("background-image", "url(img/" + $(this).attr("id") + ".jpg)");
});

答案 2 :(得分:0)

如果有多个元素,最好使用每种方法。

$(".element").each(function(){
    $(this).css("background-image", "url(img/" + $(this).attr("id") + ".jpg)");
});

答案 3 :(得分:-1)

$('.element').each(function (index, element) {
    $(element).css("background-image", "url(img/" + $(element).attr('id') + ".jpg)");
});