2013-08-31 47 views
0

我需要以下问题的帮助。我需要改变css属性(背景),取决于父类的类名。这是我的代码。根据父类更改css

HTML

<div id="types"> 
    <ul> 
    <li class='car'><a href='#'>Car</a></li> 
    <li class='bus'><a href='#'>Bus</a></li> 
    </ul> 
</div> 

我需要改变a标签background-image。如果我在li.car,那么背景将是images/car.png,如果在li.bus,那么images/bus.png

我找不出问题在哪里。这是我如何开始的,而且这是有效的。

$('#types ul li a').css('background', "url('./images/skills/cooking.png') 
    center center no-repeat"); 

但是,当我将其更改为类似的东西,它不会工作:

$('#types ul li a').css('background', 
    "url('./images/skills/'+($(this).parent().attr('class'))+'.png') 
    center center no-repeat"); 

有什么不对?

回答

1

除非您特别调用evalFunction构造函数,否则引号内的代码将不会执行。尝试在报价外面碰撞它,它应该工作。

$('#types ul li a').each(function() { 
     $(this).css('background', "url('./images/skills/" + ($(this).parent().attr('class')) + ".png') center center no-repeat"); 
    }); 
+0

我在那里写了糟糕的报价。我有这个代码,但它不起作用。 :/ –

+0

啊,你需要为'$(this)'创建一个上下文。我不幸在手机上,所以我不能完全有帮助,但如果你使用'.each'并改变CSS,它应该可以工作。 '$(“#types ul li a”)。each(function(){$(this).css();});' – AdrianCooney

+0

你是最棒的!非常感谢:) –