jQuery 的attr()与css()的区别

来源:互联网 发布:闪点悖论 知乎 编辑:程序博客网 时间:2024/05/18 23:25

1.attr是用来获得或设置标签属性的(attribute的缩写)

var myId = $("#myId");

myId.attr("data-name", "baidu");

// 设置属性名data-name,值baidu

// 结果为 : <div id="myId" data-name="baidu"></div>

 

var attr = myId.attr("data-name"); // 获取

 

相对于

var myId = document.getElementById("myId");

myId.setAttribute("data-name", "baidu"); // 设置

myId.getAttribute("data-name"); // 获取

 

2.css是设置元素的style样式的

var myId = $("#myId");

myId.css("background-color", "red"); // 设置背景颜色为红色

var bg = myId.css("background-color"); // 获取背景颜色

 

相对于

var myId = document.getElementById("myId");

myId.style.backgroundColor = "red"; // 设置

var bg = myId.style.backgroundColor; // 获取