Hoe krijg ik het data-id attribuut?

Ik gebruik de jQuery quicksand plugin. Ik moet de data-id van het geklikte item krijgen en doorgeven aan een webservice. Hoe krijg ik de data-id attribuut? Ik gebruik de .on() methode om de klik gebeurtenis voor gesorteerde items te re-binden.

$("#list li").on('click', function() {
  //  ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
  alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
  <li data-id="id-40" class="win">
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
    </a>
  </li>
</ul>
Oplossing

Om de inhoud van het attribuut data-id te krijgen (zoals in <a data-id="123">link</a>) moet je gebruik maken van

$(this).attr("data-id") // will return the string "123"

of .data() (als je nieuwere jQuery >= 1.4.3 gebruikt)

$(this).data("id") // will return the number 123

en het deel na data- moet kleine letters zijn, bijv. data-idNum werkt niet, maar data-idnum wel.

Commentaren (15)

Als we deze attributen willen opvragen of bijwerken met behulp van bestaande, native JavaScript, dan kunnen we dat doen met de methoden getAttribute en setAttribute, zoals hieronder getoond:

Door middel van JavaScript

<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>

Door jQuery

// Fetching data
var fruitCount = $(this).data('fruit');
OR 
// If you updated the value, you will need to use below code to fetch new value 
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).attr('data-fruit','7');

Lees deze documentatie

Commentaren (0)

Ik gebruik $.data - http://api.jquery.com/jquery.data/

//Set value 7 to data-id 
$.data(this, 'id', 7);

//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Commentaren (0)