如何使用JavaScript添加布尔属性 [英] How to add boolean attribute using JavaScript

查看:85
本文介绍了如何使用JavaScript添加布尔属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何使用JavaScript添加布尔属性?例如,您如何更改:

< p> to < p contenteditable>



< p> to < p data-example>

解决方案

通常,您可以使用元素.setAttribute('attributeName','value') element.propertyName = value 切换元素的属性或属性。



布尔属性



对于布尔属性,请使用相同名称的值设置属性:

  element.setAttribute('disabled','disabled'); 

删除布尔属性的方式与其他属性相同:

  element.removeAttribute('disabled'); 

但是,您的两个示例都不是

contenteditable



contenteditable 不是布尔属性它是一个枚举属性。它的可能值是空字符串truefalse



在这种情况下, setAttribute 看起来有点矫枉过正,您可以使用它:

  element.setAttribute('contenteditable','true'); 
//撤销:
element.removeAttribute('contenteditable');

contenteditable 属性的属性名称是 contentEditable (注意大写 E ),它识别值 'true''false''inherit' - 所以您可以使用:

  element.contentEditable ='true'; 
//撤销:
element.contentEditable ='false';

请注意'true'和<$
$ b

data-example 对于数据示例属性,您可以使用:

$ b b $ b

  element.setAttribute('data-example','some value'); //值应该是一个字符串
//撤消:
element.removeAttribute('data-example');

或者,在支持 dataset 的浏览器中请参阅 http://caniuse.com/dataset 中以浅绿色突出显示的内容),您可以使用:

  element.dataset.example ='some value'; 


How do you add boolean attributes using JavaScript? For example, how can you change:

<p> to <p contenteditable>

<p> to <p data-example>

解决方案

In general, you can use element.setAttribute('attributeName', 'value') or element.propertyName = value to toggle an element’s attributes or properties.

Boolean attributes

For boolean attributes, set the attribute with the same-named value:

element.setAttribute('disabled', 'disabled');

Removing a boolean attribute works the same way as other attributes:

element.removeAttribute('disabled');

However, neither of your two examples are boolean attributes!

contenteditable

contenteditable is not a boolean attribute, it’s an enumerated attribute. Its possible values are the empty string, "true", and "false".

While setAttribute seems overkill in this case, you could use it:

element.setAttribute('contenteditable', 'true');
// to undo:
element.removeAttribute('contenteditable');

The property name for the contenteditable attribute is contentEditable (note the capital E), and it recognizes the values 'true', 'false', and 'inherit' — so you could just use:

element.contentEditable = 'true';
// to undo:
element.contentEditable = 'false';

Note that 'true' and 'false' are strings here, not booleans.

data-example

For the data-example attribute, you could use:

element.setAttribute('data-example', 'some value'); // the value should be a string
// to undo:
element.removeAttribute('data-example');

Or, in browsers who support dataset (see the ones highlighted in light green on http://caniuse.com/dataset), you could use:

element.dataset.example = 'some value';

这篇关于如何使用JavaScript添加布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆