【问题标题】:Defining img custom property定义 img 自定义属性
【发布时间】:2013-04-04 12:39:12
【问题描述】:

我正在尝试为 DOM 元素“img”分配属性“itemId”

这里是代码

var img = document.createElement('IMG');
window.console.log(itemId);
img.itemId = itemId;
window.console.log(img.itemId); 

执行后控制台包含以下消息:

41
http://example.domain/41

example.domain - 是我网站的地址。

此问题出现在 Opera 和 Mozilla 中,但在 Chrome 中此代码工作正常(img.itemId == 41)。示例:http://jsfiddle.net/uwPY5/

谁能解释这是怎么回事?

【问题讨论】:

  • 感谢@Rodik - 你的回答很有帮助!
  • 也感谢@shadow-wizard)

标签: javascript dom opera mozilla


【解决方案1】:

非常奇怪的行为,但尝试标准方式:

img.setAttribute("itemId", itemId);

为了与 HTML5 兼容,您应该像这样为属性名称添加前缀:

img.setAttribute("data-itemId", itemId);

然后再读一遍:

var itemId = img.getAttribute("data-itemId");

【讨论】:

  • 此外,您应该始终像这样为自定义属性添加前缀:data-itemId
  • @Rodik 为什么?它写在哪里?我第一次看到它只在 jQuery 中使用。
  • A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z). w3.org/TR/2011/WD-html5-20110525/…
  • HTML5规范文档中写的。
  • @Rodik 谢谢,没有意识到这一点(永远不会停止学习!)编辑了我的帖子以反映这一点,但仍然使用旧时尚 setAttribute 来支持旧版浏览器。
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 2011-07-19
  • 1970-01-01
相关资源
最近更新 更多