className vs. get/setAttribute method
className vs. get/setAttribute method
我遇到了两种获取attribute值的方法:第一个是:
document.getElementById("id").getAttribute("class");
document.getElementById("id").setAttribute("class", "newClass");
另一种:
document.getElementById("id").className;
两者都可以用于设置和获取类值或任何其他值。是否存在更可取的具体情况?一个比另一个快吗?它们有什么不同?为什么有两种方法?
他们做不同的事情。.getAttribute('name')
获取属性,而.name
获取属性。
属性是在创建元素时由HTML代码中的属性设置的初始值。属性是当前值,该值可能在创建元素后发生了更改。
对于某些属性,属性会随属性一起更改,但对于某些属性来说,属性和属性是单独的值:
window.onload = function(){
var el = document.getElementById("id");
console.log("Attribute: " + el.getAttribute("value"));
console.log("Property: " + el.value);
console.log('Changing property');
el.value = 'b';
console.log("Attribute: " + el.getAttribute("value"));
console.log("Property: " + el.value);
};
<input type="text" id="id" value="a"></div>
一次问4个问题不是个好主意。
是否存在更可取的具体情况?
一般来说,设置属性是首选,因为它更简单,历史上更可靠。
一个比另一个快吗?
从逻辑上讲,设置属性应该比调用方法更快,但差异可能可以忽略不计,甚至无关紧要。
它们有什么不同?
setAttribute设置属性值。属性反映在属性中。从历史上看,设置属性并不总是更改属性,反之亦然。
为什么有两种方法?
属性在javascript之前就存在于HTML中,您可以将它们视为标记中的内容。DOM属性主要是属性的反射。例如,从前,表单控件的value属性反映默认值,而value属性反映其实际值。但其中许多差异正在消失。
设置一个不是标准同名属性的反射的属性不会创建该名称的属性(除了几个例外,即该属性的名称与其相关属性不同,如class/className和for/htmlFor)。
有很多关于属性与属性的文章,很多都被jQueryattr与prop的问题破坏了,但如果你读够了,你就会明白了。
如果您的代码可以更改不同的属性,那么您将使用document.getElementById("id").getAttribute(myVar); //myVar can be "class"
document.getElementById("id").setAttribute(myVar, myValue); //myValue can be "newClass"
如果你知道你要换班,你可以使用document.getElementById("id").className;
编辑:正如上面的答案所指出的,属性是在HTML上设置的,当更改属性时,属性通常也会更改。
一个比另一个快吗?
我刚刚看到一个网页(https://jsperf.com/style-vs-classname/4)测试3种不同方式实现的速度
// css: .hide { display: none }
document.getElementById("id").style.display = "none";
document.getElementById("id").setAttribute( "class", "hide" );
document.getElementById("id").className( "hide" );
早在2010年,IE 6-7和Opera的第一个替代方案是最快的。
在我的浏览器(Ubuntu Chromium 64位上的Chrome 47.0.2526.73)中,第一种选择比第二种快2.7倍,比第三种快4倍。
自己试试吧!
- document.applet.method在Mounatin Lion上抛出safari 6+JDK7异常
- 当method=post时,jQueryAjax返回404
- Javascript setattribute-名称和值无效
- 调用laravel{{action(Controller@method}}通过传递vue.js数组中的变量
- setAttribute和video.src用于更改IE9中不起作用的视频标记源
- TinyMCE->无法读取属性'setAttribute'为null
- Java eqivalent method of “splice(a,b,..)“在 JavaScript 方法中
- Javascript中的setAttribute和点符号有什么区别
- JavaScript Loop to setData method
- Extending jQuery.fn.method
- Javascript 错误:catChildNotes[y].setAttribute 不是一个函数
- Javascript - jQuery preventDefault method
- 如何显示Ajax Get-Method中的数据
- Javascript method win.validate();
- fine uploader uploadStoredFiles method
- jQuery deferred method and ajax beforeSend()
- 如何使用setAttribute更新对象中的一个值
- 调用Action Method,关闭对话框并刷新父项
- JavaScript "Object Method"
- className vs. get/setAttribute method