2013-02-13 57 views
4

我有一堆div.textBox,我想将数据属性应用到它。使用js在div上设置数据属性

这是我想结束了一下:

<div class="text" data-stellar-ratio="2"> 

我已经试过:

document.getElementByClassName('text').dataset.stellar.ratio = "2"; 

但它不工作...

帮助!

+0

尝试'element.setAttribute( '数据恒星比', '东西');' – MCL 2013-02-13 18:09:44

+0

这应有助于:http://stackoverflow.com/questions/710275/how-to-add-update -an-attribute-to-html-element-using-javascript – tymeJV 2013-02-13 18:10:40

+1

应该是'.dataset.stellarRatio ='2';' – Shmiddty 2013-02-13 18:12:17

回答

2
document.getElementsByClassName('text')[0].setAttribute('dataset-stellar-ratio', '2') 
+0

这也做到了! – PMaly 2013-02-13 18:38:08

0

您拼写为getElementsByClassName错误,您需要遍历元素集合并将stellar.ration更改为stellarRatio

var eles = document.getElementsByClassName('text'); 
for (var x = 0; x < eles.length; x++){ 
    eles[x].dataset.stellarRatio = "2"; 
} 
+0

没有为我工作。谢谢。 – PMaly 2013-02-13 18:26:49