我可以使用HTML5 data- *属性作为布尔属性吗? [英] Can I use HTML5 data-* attributes as boolean attributes?

查看:108
本文介绍了我可以使用HTML5 data- *属性作为布尔属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个自定义布尔属性来标记一个元素的内容是可编辑的。我知道 data - * 属性,但不确定它们是否需要值。我不需要 data-is_editable =false,因为这个属性的缺失是等价的。我只关心它是否为真实(如果该属性存在)。我知道我可以使用其他属性,比如 class ,但我不想看起来稍微不合适(纠正我,如果我错了)。



这里是我正在阅读的资源,也许是错误的文档,或者我忽略了我要查找的信息:
http://www.w3.org/html/wg/drafts/html/ master / dom.html#custom-data-attribute

例如,这是合法有效吗?

 < div data-editable data-draggable>我的内容< / div> 


解决方案

您显示的示例是有效的。 (就像在表单中使用 disabled checked )一样。只有 xHTML 强制存在一个值)

尽管返回的值不是布尔值。当你查询这个资源时,你会得到一个空字符串,用于任何空的 data - * 属性。



赞所以:

  domNode.dataset.draggable; // log
domNode.dataset.notAdded; // log null

所以,你只需要检查它:

  var isDraggable =(domNode.dataset.draggable!= null)

编辑



以前没有告诉过的笨蛋。但是,如果你想要一个布尔值,你可以检查该属性是否存在:

  domNode.hasAttribute(data-draggable) ; 


I want to use a custom boolean attribute to mark an element's contents as editable. I'm aware of the data-* attributes, but wasn't sure if they require a value. I don't need data-is_editable="false", as the lack of the attribute would be equivalent. I only care if it's "true" (if the attribute exists). I know I can use other attributes like class but I don't want to as it seems slightly inappropriate (correct me if I'm wrong about that).

Here's the resource I'm reading, maybe it's the wrong document or I've overlooked the information I'm looking for: http://www.w3.org/html/wg/drafts/html/master/dom.html#custom-data-attribute

So for example, is this legal and valid?

<div data-editable data-draggable> My content </div>

解决方案

The example you show is valid. (Just like using disabled or checked in a form. Only xHTML force the presence of a value)

Although, the value returned is not a boolean. When you query this resource, you'll get an empty string for any empty data-* attributes.

Like so:

 domNode.dataset.draggable; // log ""
 domNode.dataset.notAdded; // log null

So, you just have to check it:

var isDraggable = (domNode.dataset.draggable != null)

Edit

Stupid to haven't tell it before. But, you can just check if the attribute exist if you want a boolean:

domNode.hasAttribute("data-draggable");

这篇关于我可以使用HTML5 data- *属性作为布尔属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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