在jQuery中,itemscopes、attributes或properties是什么东西?

In jQuery, what kind of things are itemscopes, attributes or properties?

如果我想动态地将一个元素设置为新的项目范围并赋予它一个项目类型,从 jQuery 的角度来看 itemscope 是什么?换句话说,我应该使用 .attr("itemscope", "") 还是 .prop("itemscope", true)

举个例子,假设我想在我的 body 标签中添加一个 itemscope 并为其指定类型 WebPage:

<body itemscope itemtype="http://schema.org/WebPage">

我可以使用 $("body").attr("itemtype", "http://schema.org/WebPage") 作为类型,但是 itemscope 呢?

问题是,当我使用 .prop('itemscope', true) 时,我没有看到这些变化反映在 HTML 中(即 DOM 中没有可见的变化),而使用 .attr('itemscope', '') 显示更改,但作为属性。换句话说,itemscope='' 而不是 itemscope.

itemscope 添加到具有 JS/jQuery 的元素的有效方法是什么?

var d = $("div");

d.attr('itemtype', 'http://schema.org/WebPage');
d.attr('itemscope', '');
d.prop('itemscope', true);
console.log(d.attr('itemtype'));
console.log(d.attr('itemscope'));
console.log(d.prop('itemscope'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div/>

itemscope attribute 是一个 布尔属性

这意味着它可以通过多种方式指定(在 HTML 语法中):

  • itemscope
  • itemscope=""
  • itemscope=''
  • itemscope=itemscope
  • itemscope="itemscope"
  • itemscope='itemscope'

(并且在某些位置具有 upper/mixed 大小写和额外空格的变体也是可能的)

(参考资料来自 HTML 5.1:2.4.2. Boolean attributes, 8.1.2.3. Attributes

要用 JavaScript 添加它,请参阅问题 How to add boolean attribute using JavaScript