Estoy usando el complemento jQuery Quicksand . Necesito obtener la identificación de datos del elemento en el que se hizo clic y pasarlo a un servicio web.
¿Cómo obtengo el atributo data-id? Estoy usando el método .on() para volver a vincular el evento de clic para los elementos ordenados.
$("#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>Para obtener el contenido del atributo data-id (como en <a data-id="123">link</a> ), debe usar
$(this).attr("data-id") // will return the string "123" o .data() (si usa jQuery más nuevo> = 1.4.3)
$(this).data("id") // will return the number 123 y la parte posterior a data- debe estar en minúsculas, por ejemplo, data-idNum no funcionará, pero data-idnum sí.
Si queremos recuperar o actualizar estos atributos usando JavaScript nativo existente, entonces podemos hacerlo usando 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');Nota IMPORTANTE. Tenga en cuenta que si ajusta el atributo de data- dinámicamente a través de JavaScript, no se reflejará en la función data() jQuery. También debe ajustarlo a través de la función data() .
<a data-id="123">link</a>JavaScript:
$(this).data("id") // returns 123 $(this).attr("data-id", "321"); //change the attribute $(this).data("id") // STILL returns 123!!! $(this).data("id", "321") $(this).data("id") // NOW we have 321