2016-01-10 23 views
2

我需要从属性设置元素的背景色。在当前我试图:如何从JQuery中的属性设置CSS值

$('[myAttr]').css('background-color', $(this).attr('myAttr')); 

$(this).attr('myAttr')返回未定义。

有没有办法做到这一点?

+2

发布您的HTML和脚本。 “这个”可能不是指你认为它指的是什么。 – jumbopap

+0

提供代码片段,因为它尚未清楚这是指什么。 – amitguptageek

回答

1

在你的例子中,this没有引用[myAttr]元素,因为没有范围。

你可以通过一个匿名函数(让你有机会获得this),并返回属性值:

$('[myAttr]').css('background-color', function() { 
    return $(this).attr('myAttr'); 
}); 
+1

谢谢你,这正是我需要的。 –

0

this是不相关的回调之外。做这样的事情...

$('[myAttr]']).each(function() { 
    $(this).css('background-color', $(this).attr('myAttr')) 
}) 
0

this可能不是指元素。尝试如下。

var elm = $('[myAttr]'); 
elm.css('background-color', elm.attr('myAttr'));