js实现attr
实现 attr 方法
在 JavaScript 中,可以通过原生 DOM 操作或 jQuery 类似的方式实现元素的属性(attr)获取和设置功能。以下是两种常见的实现方式:
原生 JavaScript 实现
通过 getAttribute 和 setAttribute 方法实现属性的获取和设置:
function attr(element, attributeName, value) {
if (value === undefined) {
return element.getAttribute(attributeName);
} else {
element.setAttribute(attributeName, value);
return element;
}
}
使用示例:
const div = document.querySelector('div');
attr(div, 'id', 'myDiv'); // 设置属性
console.log(attr(div, 'id')); // 获取属性,输出 'myDiv'
链式调用扩展
如果需要支持链式调用(类似 jQuery),可以扩展 Element.prototype:
Element.prototype.attr = function(attributeName, value) {
if (value === undefined) {
return this.getAttribute(attributeName);
} else {
this.setAttribute(attributeName, value);
return this;
}
};
使用示例:
document.querySelector('div')
.attr('id', 'myDiv')
.attr('class', 'container');
支持多属性设置
如果需要一次性设置多个属性,可以扩展功能:
function attr(element, attributeName, value) {
if (typeof attributeName === 'object') {
for (const key in attributeName) {
element.setAttribute(key, attributeName[key]);
}
return element;
} else if (value === undefined) {
return element.getAttribute(attributeName);
} else {
element.setAttribute(attributeName, value);
return element;
}
}
使用示例:
attr(document.querySelector('div'), {
id: 'myDiv',
class: 'container'
});
注意事项
- 原生
getAttribute返回的是字符串,而 jQuery 的attr可能返回其他类型(如checked返回布尔值)。 - 修改原型(
Element.prototype)可能与其他库冲突,需谨慎使用。 - 现代前端开发推荐使用
dataset处理自定义数据属性(data-*)。






