문제

I have code that looks like this:

<ul class="effects-list">
   <li data-creative="1">Creative</li>
   <li data-uplifted="3">Uplifted</li>
   <li data-energetic="3">Energetic</li>
</ul>

Then Javascript to read the data attributes:

$(function() {

  var effectData = $('.effects-list li');
  var creative = effectData.data("creative");
  var uplifted = effectData.data("uplifted");
  var energetic = effectData.data("energetic");

  console.log(creative);
  console.log(uplifted);
  console.log(energetic);

});

I end up with this in the console log:

1
undefined
undefined

Why is the script reading the information in the first li element but not the second two?

What do I have wrong and how do I solve the problem?

Here is a fiddle with the code above. I am using jQuery 2.1.

도움이 되었습니까?

해결책

Since you are using the getter version of data(), it will look only at the first element in the given set, which does not have the said data attributes.

.data(key)

Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

The solution is to use an attribute exists selector to target the correct element then fetch the data value. something like

var uplifted = effectData.filter('[data-uplifted]').data("uplifted");

Demo: Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top