所以如果要想最开始的布尔属性⽣效,我们需要如下写法,即采⽤框架提供的指令来书写那么框架内部对布尔属性是怎么处理的呢?以jquery跟vue为例
jquery
设置布尔属性:$('input').attr('readonly', true)
取消布尔属性:$('input').attr('readonly', false)
attr: function( elem, name, value ) {
var ret, hooks,
nType = deType;
// Fallback to prop when attributes are not supported
if ( Attribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// 兼容布尔属性
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ LowerCase() ] ||
( pr.st( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
return;
}
// 如果是布尔属性,则⾛hooks内的⽅法
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = ( elem, name ) ) !== null ) { return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
}
// Hooks for boolean attributes,可以通过attr('readonly', false)来关闭布尔属性var boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// 即$('input').attr('readonly', false)去掉只读
} else {
elem.setAttribute( name, name );
}
return name;
}
}
vue
function setAttr (el: Element, key: string, value: any) {
debugger
if (el.tagName.indexOf('-') > -1) {
baseSetAttr(el, key, value)
} else if (isBooleanAttr(key)) {
// 判断isBooleanAttr⽅法是否是布尔属性
// set attribute for blank value
// e.g. Select one
/
/ 通过isFalsyAttrValue⽅法判断值是否是false与null,如果isFalsyAttrValue返回为true则表⽰传⼊的值//是false or null,则删除当前布尔属性,否则设置当前的属性值为el.setAttribute(key, value)
if (isFalsyAttrValue(value)) {
} else {
// technically allowfullscreen is a boolean attribute for ,
// but Flash expects a value of "true" when used on tag
value = key === 'allowfullscreen' && el.tagName === 'EMBED'
? 'true'
: key
el.setAttribute(key, value)
}
} else if (isEnumeratedAttr(key)) {
jquery的attr属性
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true')
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
} else {
el.setAttributeNS(xlinkNS, key, value)
}
} else {
baseSetAttr(el, key, value)
}
}
export const isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
)
export const isFalsyAttrValue = (val: any): boolean => {
return val == null || val === false
}
通过vue及jquery的处理⽅式不难看出其它框架,都是对布尔属性做了特殊处理;
总结:
布尔属性是否⽣效跟属性的value值⽆关;只跟是否存在该属性有关;
即,
,
都是⼀样的效果
input标签上常⽤的布尔属性有required、readonly、multiple、autofocus、checked、disabled

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。