I'm mit dem jQuery Quicksand-Plugin. Ich brauche, um die Daten-ID des angeklickten Elements zu erhalten und übergeben Sie es an einen Webservice.
Wie erhalte ich das Attribut data-id? Ich verwende die Methode .on()
, um das Klick-Ereignis für sortierte Elemente neu zu binden.
$("#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>
Um den Inhalt des Attributs data-id
(wie in <a data-id="123">link</a>
) zu erhalten, müssen Sie verwenden
$(this).attr("data-id") // will return the string "123"
oder .data()
(wenn Sie neueres jQuery >= 1.4.3 verwenden)
$(this).data("id") // will return the number 123
und der Teil nach data-
muss klein geschrieben werden, z.B. wird data-idNum
nicht funktionieren, aber data-idnum
schon.
Wenn wir diese Attribute mit Hilfe von vorhandenem, nativem JavaScript abrufen oder aktualisieren wollen, dann können wir dies mit den Methoden getAttribute und setAttribute tun, wie unten gezeigt:
Durch 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>
Durch 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');
Ich verwende $.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