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

used this approach for 1000 element to set their attribute. All working fine, but .attr() takes 10ms to execute, I need to optimize it, is there any alternative for .attr().

Thanks in advance

4

3 回答 3

3

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

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

this.setAttribute("id","name");
this.style.visibility =  'hidden';
于 2013-11-13T06:06:10.300 回答
2

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

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

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

于 2013-11-13T06:17:39.847 回答
1

与其直接更改属性,不如向那些定义为具有您想要的属性的元素添加一个类?

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

就是这样:

javascript:

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

随附的CSS:

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

此外,您在 attr() 调用中缺少括号,并且需要将连字符的 stroke-width 方法放在引号中,如下所示:

$(this).attr({id:'name', visibility:'hidden', fill:'black', 'stroke-width':2});
于 2013-11-13T06:26:33.200 回答