Как да получа атрибута data-id?

Използвам плъгина jQuery quicksand. Трябва да получа data-id на щракнатия елемент и да го предам на уеб услуга. Как да получа атрибута data-id? Използвам метода .on() за повторно свързване на събитието щракване за сортирани елементи.

$("#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>
Решение

За да получите съдържанието на атрибута data-id (като в <a data-id="123">link</a>), трябва да използвате

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

или .data() (ако използвате по-нова версия на jQuery >= 1.4.3)

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

и частта след data- трябва да е с малки букви, например data-idNum няма да работи, но data-idnum ще работи.

Коментари (15)

Ако искаме да извличаме или актуализираме тези атрибути, като използваме съществуващ роден JavaScript, можем да го направим, като използваме методите getAttribute и setAttribute, както е показано по-долу:

чрез 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>

чрез 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');

Прочетете тази документация

Коментари (0)

Използвам $.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
Коментари (0)