简体   繁体   中英

Simple javascript loop not working

I'm not that experienced yet with JavaScript, so I'm probably overlooking something here:

var products = document.getElementsByClassName('product');
var productsLength = products.length;

for(var i = 0; i < productsLength; i++){
  var productGender = products[i].attr('data-gender');

  if(productGender === triggerVal){
    console.log('yes');
  } else {
    console.log('no');
  }
};

It says: products[i].attr is not a function

I should be able to access it right? The product is just a list item.

Thanks!

attr is a jQuery method, use getAttribute

http://www.w3schools.com/jsref/met_element_getattribute.asp

 var productGender = products[i].getAttribute('data-gender');

你需要什么,你使用了jquerys .attr()

By far the easiest way to get data-xyz attributes for an element is to use .dataset object

eg in your case

var productGender = products[i].dataset.gender;

MDN - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

usual warnings - IE11+ only (other browsers have supported it for years) - there's no polyfill

if you need early IE support, then use = getAttribute("data-gender"); as others have suggested

It's because you use Jquery function on DOM element. You should either use native javascript function to retrieve attribute value or you can convert element to Jquery object and then keep using Jquery.

So, instead of

products[i].attr('data-gender');

you can:

$(products[i]).attr('data-gender');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM