使用jQuery attr()来设置“css”

时间:2014-07-10 22:35:39

标签: jquery css attr

我正在阅读“jQuery Pocket Reference”一书,O'Reilly,2011 在第15页,它说

'例如,调用attr(" css",{backgroundColor:" grey"})与调用css相同({backgroundColor:" gray& #34;})'

但是我不能让attr(“css”,{})起作用。我的测试代码:http://jsfiddle.net/4UMN3/4/

$(function() {
$("#btnChangeColor").click(function () {
$("#spanText").attr("css", { backgroundColor: "gray" });

 });

});

css()方法正常,http://jsfiddle.net/4UMN3/5/

由于

7 个答案:

答案 0 :(得分:12)

替换:

$("#spanText").attr("css", { backgroundColor: "gray" });

$("#spanText").attr('style',  'background-color:gray');

答案 1 :(得分:4)

可能,它本来就是

$("#spanText").attr('style', 'background-color:gray');

这可能有用,但有一些问题:

  • 最好更改style属性,而不是style属性。
  • 它将替换所有以前设置的内联样式。

然后,如果您使用jQuery,最好使用css方法:

$("#spanText").css('background-color', 'gray');

style属性在vanilla-js中很有用:

document.getElementById("spanText").style.backgroundColor = 'gray';

答案 2 :(得分:2)

我认为jQuery的.attr()只能影响元素的属性。 HTMLElements不知道名为&#34; css&#34;的属性。 (意思是<div css="something"></div>)。

因此,正确的用法是

$("#spanText").attr("style",{backgroundColor:"gray"});

但这会输出

<span id="spanText" style="[object Object]">This is a test</span>

实际有效的例子是

$("#spanText").attr("style","background-color:gray;");

答案 3 :(得分:1)

&#13;
&#13;
$("#id").attr('style',  'color:red;cursor:pointer');
&#13;
&#13;
&#13;

答案 4 :(得分:0)

=&GT; .css方法修改了style属性而不是&#34; css&#34;

$().att('style' , 'backgroundColor : gray');

=&GT;在html

中没有css属性这样的东西

答案 5 :(得分:0)

您使用jQuery,因此必须使用 css 而不是 attr ,因为 css 添加 属性 ,但是 attr 将替换所有 style (如果存在的话)!

答案 6 :(得分:0)

<style>
    .newClass{
    color:#fff;
    }
    .test2{
    color:red;
    }
    .newclass{
    color:blue;
    }
</style>

<script>
$(document).ready(function(){

    //get style and class name in alert
      $('#attr').click(function () {
        alert($('h3').attr("style"));
        alert($('h3').attr("class"));
      });

     //set css property
     $("#setcss").click(function(){
        $("#test").css({"background-color": "#000", "color": "teal"});
      });

      //change class name property
      $('#changeclassname').click(function(){
        $('#test3').removeClass('test2').addClass('newclass');
      });
});


</script>


<!--get style and class name in alert-->
<h3 class="test" style="color: white; background: red;">This is the tag and this will be our tag</h3> 

<button id="attr">get Attribute</button>


<!--set css property-->
<p id="test" class="test1">This is some <b>bold</b> text in a paragraph.</p>

<button id="setcss">set Attribute</button>


<!--change class name property-->
<p id="test3" class="test2">This is some text in a paragraph.</p>

<button id="changeclassname">set Attribute</button>