HTML中是否有诸如自定义布尔属性之类的东西?

Is there a thing such as custom boolean attributes in HTML?

在HTML5中我们可以使用自定义data-* attributes。但是,据我了解并考虑到它们是 属性 我希望它们需要一个字符串值。 HTML 中是否有替代方案允许自定义 属性 ,即布尔值属性,例如 checkedrequiredhidden 和很快。

假设我有一个学校网站。假设我希望页面上的某些元素在用户是教师时与用户交互,但在用户是学生时则不行。在 JavaScript 中,将事件附加到某些具有 属性 teacher-can-interact 或类似元素的元素会很好。我显然知道我可以使用 类 或数据属性,但 类 在语义上看起来并不漂亮,并且在我看来具有 yes 值的数据属性是荒谬的 - 这就是属性是为了.

那么,是否有任何方式或计划支持自定义属性? (不是属性。)

编辑:属性 我指的是 jQuery 自版本 1.6(.1) 以来的区别,其中属性主要是 布尔属性 。我希望(想要)下面的代码 return 为真,但它 return 是一个空字符串。

console.log($("div").prop("data-intrusive"));
console.log($("div").attr("data-intrusive"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-intrusive></div>

显然,有一些解决方法,例如检查 typeof 之类的。但是,如果有一种方法可以创建 return true 或 false in JavaScript 而不是字符串的自定义布尔属性,那就太好了。

在实践中,您可以使用任何您想要的自定义属性,它会起作用:

console.log(document.querySelector('div').getAttribute('foo'));
<div foo="bar">My div</div>

从技术上讲,它是无效的 HTML 标记。没有计划支持自定义属性,这就是数据属性的目的。您可以在代码中将属性和数据属性设置为 true

element.setAttribtue('teacher-can-interact', true);
element.dataset['teacher-can-interact'] = true;

但是它们总是从 HTML 中被解释为一个字符串——这就是 HTML 的工作方式,它不是一种编程语言,也没有数据类型的概念。

您可以使用 element.hasAttribute("name"); 使用普通的 javascript 来做到这一点 看看这个小提琴:https://jsfiddle.net/7fax95ve/1/

对于 DOM 属性,如 checked、selected、disabled 或 hidden,您将获得布尔值

$("div").attr("data-intrusive");

.attr() 将获取属性值而不是布尔值。 .attr() 将尝试获取 data-intrusive 的值,如果您在 DOM 中观察到 data-intrusive 的值,则它是空字符串

<div data-intrusive="">1</div>

.prop() 将 return 布尔属性的布尔值和 属性 所有其他属性的值

例如考虑下面的例子

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-intrusive style="color:red" hidden>1</div>

JS:

console.log($("div")[0].outerHTML) //output- <div data-intrusive="" style="color:red" hidden="">1</div>

console.log($("div").prop('style'));// output-CSSStyleDeclaration {0: "color", alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: ""…}
console.log($("div").attr('style'));//output- color:red


console.log($("div").prop('hidden'));//true
console.log($("div").attr('hidden'));//hidden

console.log($("div").attr('data-intrusive'));//empty string as expected
console.log($("div").prop('data-intrusive'));//undefined as expected, as there is no property value

要获得预期结果,请使用 hasAttribute('data-intrusive') 获取字符串值或设置 属性 获取数据侵入布尔值以获取 .prop('data-intrusive') 值作为布尔值

//if it is a string value
console.log($("div")[0].hasAttribute('data-intrusive'));

//if it is boolean ,then it is return the same
$("div").prop('data-intrusive','fasle');
console.log($("div").prop('data-intrusive'));

Codepen - http://codepen.io/nagasai/pen/VjgNwx