2013-04-09 54 views
45

我可以在沒有jQuery的情況下訪問數據屬性嗎?無jQuery訪問'數據'屬性

用jQuery很容易,但是我看不到沒有jQuery的地方。

如果我在Google上搜索'沒有jQuery',我只能看到jQuery的例子。

這有可能嗎?

+1

這是舊的,但它可以讓你去:http://html5doctor.com/ html5-custom-data-attributes/ – dsdsdsdsd 2013-04-09 20:53:10

回答

76

here我發現這個例子:

<div id='strawberry-plant' data-fruit='12'></div> 
<script> 
    // 'Getting' data-attributes using getAttribute 
    var plant = document.getElementById('strawberry-plant'); 
    var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12' 
    // 'Setting' data-attributes using setAttribute 
    plant.setAttribute('data-fruit', '7'); // Pesky birds 
</script> 

所以看上去非常可行的。

+2

第一個答案+適用於所有瀏覽器 – user2143356 2013-04-09 21:30:03

+0

這似乎是正確的方法。此外,您可能需要能夠執行如下操作:document.getElementById('strawberry-plant')。setAttribute('data-fruit','Some Data Here'); – sage88 2014-03-05 04:56:29

21

您可以使用數據集屬性。如:

element = document.getElementById("el"); 
alert(element.dataset.name); // element.dataset.name == data-name 
+6

查看對'dataset'的支持:http://caniuse.com/dataset – 2013-04-09 20:56:29

+3

注意:儘管完全正確,但這隻適用於符合HTML5的瀏覽器。使用'getAttribute'方法可以在大多數瀏覽器上使用。 – fredrik 2013-04-09 20:59:02

0

我想你可以試試這個:

var ele = document.getElementById("myelement"); 
if (ele.hasOwnProperty("data")) { 
    alert(ele.data); 
} 

或使用

alert(ele['data-property']); 
+0

來自MDN文檔,它是理想的使用getAttribute方法,因爲它的速度更快,下面我引用:**另外,與將數據存儲在JS數據倉庫中相比,讀取數據屬性的性能很差。使用數據集比使用getAttribute()讀取數據要慢。** - [link](https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes) – razzbee 2016-10-16 11:20:49