-
当HTML 5中的属性是布尔属性时,这意味着什么?
2025-06-06 20:23:02 今晚世界杯
A. 根据Bob.at.Indigo.Health的评论:
对于一些应该表示布尔值的HTML属性(例如复选框的checked属性)...将其设置为false的唯一方法是省略该属性:
所有其他的赋值将被解释为true(即使这不符合HTML标准),例如:
http://jsfiddle.net/hgq4ewr1/
B. 一些 JavaScript 库可能定义特殊值,这些值也被解释为 false。
例如,使用 d3.js 可以通过使用 null 调用 attr 函数来删除属性(“将它们设置为 false”):
d3Selection.attr('checked', null);
HTMLElement的getAttribute方法如果属性不存在,则返回null或''。
另请参阅:
如何在D3.js中删除属性?
https://www.w3schools.com/jsref/prop_checkbox_checked.asp
https://www.w3schools.com/jsref/met_element_getattribute.asp
https://www.w3schools.com/jsref/met_element_setattribute.asp
checked = "checked" vs checked = true
C.如果在JavaScript中继承HTMLElement,则可以定义不同于String类型的自定义属性。另请参见https://www.webcomponents.org/introduction。
但是,我会称其为JavaScript属性而不是HTML属性,例如:
class TreezElement extends HTMLElement {
static get observedAttributes() {
return ['value'];
}
get valueProperty() {
var stringValue = this.getAttribute('value')
return this.convertFromStringValue(stringValue);
}
set valueProperty(newValue) {
var stringValue = this.convertToStringValue(newValue)
if(stringValue === null){
this.removeAttribute('value');
} else {
this.setAttribute('value', stringValue);
}
}
constructor(){
super();
}
//should be overridden by inheriting class
convertFromStringValue(stringValue){
return stringValue;
}
//should be overridden by inheriting class
//return null if the value attribute should be removed
//(="set to false")
convertToStringValue(value){
return value;
}
updateElements(newValue){
//should be implemented by inheriting class
}
attributeChangedCallback(attr, oldValue, newValue) {
if(attr==='value'){
if(newValue!==oldValue){
this.updateElements(newValue);
this.__dispatchInputEvent();
}
}
}
}