自定义一般属性

通过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
22 声望0 粉丝