问知道jQuery中css与attr之间有什么区别

2024-11-21 12:50:06
推荐回答(1个)
回答1:

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; // 获取

这里注意的是非jQuery,不能直接获取 里的值

也就是说 .css 文件里的那些值(要去写一个兼容函数才可以)。



attr: 设置和获取属性的 (attribute的缩写)。

var myId = $("#myId");
myId.attr("data-name", "baidu");
// 设置属性名data-name,值baidu
// 结果为 : 


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

相对于

var myId = document.getElementById("myId");
myId.setAttribute("data-name", "baidu"); // 设置
myId.getAttribute("data-name"); // 获取

 



望采纳 

相关问答