JavaScript 中 .attr() 的替代方法

alternative for .attr() in javascript

本文关键字:方法 attr JavaScript      更新时间:2023-09-26
$(this).attr('id':'name', visibility:'hidden', fill:'black', stroke-width:2)

对 1000 元素使用此方法来设置其属性。一切正常,但是.attr()需要10ms才能执行,我需要优化它,.attr()还有其他选择吗?

提前致谢

尝试这样的东西,为了获得更好的性能,请使用setAttribute()。

setAttribute() 方法添加指定的属性,并为其指定值。

this.setAttribute("id","name");
this.style.visibility =  'hidden';

与其直接更改属性,为什么不向那些定义为具有所需属性的元素添加一个类呢?

我在这里进行了性能测试:http://jsperf.com/attr-vs-classsnameattr() 方法在我的浏览器/操作系统上慢了 33%。

方法如下:

JavaScript:

this.className = "custom-class";
this.id = 'name';

随附的 CSS:

.custom-class {
  visiblity: hidden;
  fill: black;
  stroke-width: 2;
}

此外,attr() 调用中缺少括号,并且需要将带连字符的笔画宽度方法放在引号中,如下所示:

$(this).attr({id:'name', visibility:'hidden', fill:'black', 'stroke-width':2});

最快的替代方法是直接设置属性的相应属性。

this.id = 'name';
this.style.visibility = 'hidden';

http://jsperf.com/jquery-attr-vs-setattribute/2