Estoy usando el plugin jQuery quicksand. Necesito obtener el data-id del elemento en el que se ha hecho clic y pasarlo a un webservice.
¿Cómo puedo obtener el atributo data-id? Estoy utilizando el método .on()
para volver a enlazar el evento de clic para los elementos ordenados.
begin snippet: js hide: false console: true babel: false -->
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<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>
Para obtener el contenido del atributo data-id
(como en <a data-id="123">link</a>
) hay que utilizar
$(this).attr("data-id") // will return the string "123"
o .data()
(si usas un jQuery más reciente >= 1.4.3)
$(this).data("id") // will return the number 123
**y la parte después de data-
debe estar en minúsculas, por ejemplo, data-idNum
no funcionará, pero data-idnum
sí.
Si queremos recuperar o actualizar estos atributos utilizando JavaScript nativo existente, entonces podemos hacerlo utilizando los métodos getAttribute y setAttribute como se muestra a continuación:
A través de 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>
**A través de 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');
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