自定义属性

自定义平常属性

经由过程getAttribute猎取对应的属性

<ul>
    <li product-id="1000">basketball</li>
    <li product-id="1001">football</li>
    <li product-id="1002">volleyball</li>
    <li product-id="1003">tennis</li>
</ul>
var productList = [];
var products = document.getElementsByTagName("li");

for (var i = 0, len = products.length; i < len; i++) {
    productList.push(products[i].getAttribute('product-id'));
}

console.log(productList)

自定义data属性

经由过程getAttribute或许dataset猎取对应的属性

<ul>
    <li data-product-id="1000">basketball</li>
    <li data-product-id="1001">football</li>
    <li data-product-id="1002">volleyball</li>
    <li data-product-id="1003">tennis</li>
</ul>

<script >
var productList = [];
var products = document.getElementsByTagName("li");

for (var i = 0, len = products.length; i < len; i++) {
    // productList.push(products[i].getAttribute('data-product-id'));
    productList.push(products[i].dataset.productId);
}

console.log(productList)
</script>
    原文作者:stylever
    原文地址: https://segmentfault.com/a/1190000009137908
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞