Come ottenere l'attributo data-id?

Sto usando il plugin jQuery quicksand. Ho bisogno di ottenere il data-id dell'elemento cliccato e passarlo ad un webservice. Come posso ottenere l'attributo data-id? Sto usando il metodo .on() per ri-bindare l'evento click per gli elementi ordinati.

$("#list li").on('click', function() {
  //  ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
  alert($(this).attr("#data-id"));
});

src="https://code.jquery.com/jquery-3.3.1.slim.min.js"<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>
Soluzione

Per ottenere il contenuto dell'attributo data-id (come in <a data-id="123">link</a>) devi usare

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

o .data() (se usi jQuery >= 1.4.3 più recente)

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

e la parte dopo data- deve essere minuscola, ad esempio data-idNum non funzionerà, ma data-idnum sì.

Commentari (15)

Se vogliamo recuperare o aggiornare questi attributi usando il JavaScript nativo esistente, allora possiamo farlo usando i metodi getAttribute e setAttribute come mostrato sotto:

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

attraverso 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');

Leggi questa documentazione

Commentari (0)

Io uso $.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
Commentari (0)