Cách chính thức để đặt disabled
thuộc tính trên một HTMLInputElement
là:
var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);
// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');
Mặc dù câu trả lời của @ kaushar là đủ để kích hoạt và vô hiệu hóa HTMLInputElement
, và có lẽ thích hợp hơn cho khả năng tương thích trình duyệt chéo do lỗi lịch sử của IE setAttribute
, nhưng nó chỉ hoạt động vì Element
thuộc tính bóng Element
. Nếu một thuộc tính được đặt, thì DOM sử dụng giá trị của thuộc tính theo mặc định thay vì giá trị của thuộc tính tương đương.
Có một sự khác biệt rất quan trọng giữa các thuộc tính và thuộc tính. Một ví dụ về một HTMLInputElement
tài sản thực sự là input.value
, và dưới đây cho thấy cách thức hoạt động của bóng:
var input = document.querySelector('#test');
// the attribute works as expected
console.log('old attribute:', input.getAttribute('value'));
// the property is equal to the attribute when the property is not explicitly set
console.log('old property:', input.value);
// change the input's value property
input.value = "My New Value";
// the attribute remains there because it still exists in the DOM markup
console.log('new attribute:', input.getAttribute('value'));
// but the property is equal to the set value due to the shadowing effect
console.log('new property:', input.value);
<input id="test" type="text" value="Hello World" />
Đó là những gì nó có nghĩa để nói rằng thuộc tính bóng thuộc tính. Khái niệm này cũng áp dụng cho các thuộc tính được kế thừa trên prototype
chuỗi:
function Parent() {
this.property = 'ParentInstance';
}
Parent.prototype.property = 'ParentPrototype';
// ES5 inheritance
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
function Child() {
// ES5 super()
Parent.call(this);
this.property = 'ChildInstance';
}
Child.prototype.property = 'ChildPrototype';
logChain('new Parent()');
log('-------------------------------');
logChain('Object.create(Parent.prototype)');
log('-----------');
logChain('new Child()');
log('------------------------------');
logChain('Object.create(Child.prototype)');
// below is for demonstration purposes
// don't ever actually use document.write(), eval(), or access __proto__
function log(value) {
document.write(`<pre>${value}</pre>`);
}
function logChain(code) {
log(code);
var object = eval(code);
do {
log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);
object = object.__proto__;
} while (object !== null);
}
Tôi hy vọng điều này làm rõ bất kỳ sự nhầm lẫn nào về sự khác biệt giữa các thuộc tính và thuộc tính.