jQuery 的attr,与css

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

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

var myId = $("#myId");

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

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

// 结果为 : <div ></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; // 获取