2013-04-04 161 views
0

我试图指派属性 “项目Id” 的DOM元素 “IMG”IMG定义自定义属性

这里是代码

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/

任何人都可以解释发生了什么?

+0

感谢@Rodik - 你的回答是有帮助的! – porfirion 2013-04-04 13:00:33

+0

也感谢@ shadow-wizard) – porfirion 2013-04-04 13:07:32

回答

1

非常怪异的行为,而是尽量以标准方式:

img.setAttribute("itemId", itemId); 

为了与HTML5兼容,虽然,你应该前缀你的属性名称如下:

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

然后读回:

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

此外,你应该总是以这样的自定义属性为前缀:'data-itemId' – Rodik 2013-04-04 12:41:35

+0

@Rodik为什么?它写在哪里?我看到它仅在jQuery中使用。 – 2013-04-04 12:42:38

+0

'自定义数据属性是一个没有命名空间的属性,其名称以字符串“data-”开头,在连字符后至少有一个字符,是XML兼容的,在U + 0041到U + 005A(拉丁文大写字母A至拉丁大写字母Z).' http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#custom-data-attribute – Rodik 2013-04-04 12:44:52