Jak uzyskać atrybut data-id?

Używam wtyczki jQuery quicksand. Muszę uzyskać identyfikator klikniętego elementu i przekazać go do serwisu internetowego. Jak uzyskać atrybut data-id? Używam metody .live(), aby ponownie powiązać Zdarzenie click dla posortowanych elementów.

Html wygląda tak:

$("#list li").live('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="" />
    </a>
  </li>
</ul>
Author: Nemus, 2011-03-15

11 answers

Aby uzyskać zawartość atrybutu data-id (jak w <a data-id="123">link</a>) musisz użyć

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

Lub .data() (jeśli używasz nowszego jQuery > = 1.4.3)

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

Część po data- musi być pisana małymi literami, np. data-idNum nie zadziała, ale data-idnum zadziała.

 1270
Author: Marcel Jackwerth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-16 09:22:46

Jeśli chcemy odzyskać lub zaktualizować te atrybuty za pomocą istniejącego, natywnego JavaScript , możemy to zrobić za pomocą metod getAttribute i setAttribute, jak pokazano poniżej:

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

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

Przeczytaj tę dokumentację

 123
Author: Lalit Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-16 04:32:02

Ważna uwaga. Należy pamiętać, że jeśli dostosujesz data- atrybut dynamicznie przez JavaScript nie będzie odzwierciedlany w funkcji data() jQuery. Musisz go również dostosować za pomocą funkcji data().

<a data-id="123">link</a>

Js:

$(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
 64
Author: Serge Shultz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-29 15:22:24

Jeśli nie martwisz się o stare przeglądarki IE, możesz również użyć HTML5 dataset API

HTML

<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>

JS

var myDiv = document.querySelector('#my-div');

myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"

Demo: http://html5demos.com/dataset

Pełna lista obsługi przeglądarki: http://caniuse.com/#feat=dataset

 33
Author: Roni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-01 09:57:03

HTML

<span id="spanTest" data-value="50">test</span>

JS

$(this).data().value;

Lub

$("span#spanTest").data().value;
ANS: 50
Dla mnie działa!
 9
Author: bamossza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-19 06:16:08

Używam $.DANE - 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
 8
Author: Gjermund Dahl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-21 13:00:33
var id = $(this).dataset.id
Dla mnie działa!
 8
Author: ofir_aghai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-26 21:53:40

Dostęp do atrybutu danych za pomocą własnego id jest dla mnie trochę łatwy.

$("#Id").data("attribute");

function myFunction(){
  alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
 6
Author: Aravindh Gopi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-27 16:31:21

Zdziwiony nikt nie wspomniał:

<select id="selectVehicle">
     <option value="1" data-year="2011">Mazda</option>
     <option value="2" data-year="2015">Honda</option>
     <option value="3" data-year="2008">Mercedes</option>
     <option value="4" data-year="2005">Toyota</option>
    </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Oto działający przykład: https://jsfiddle.net/ed5axgvk/1/

 5
Author: curiousBoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-20 07:14:43

Using jQuery:

  $( ".myClass" ).load(function() {
    var myId = $(this).data("id");
    $('.myClass').attr('id', myId);
  });
 2
Author: Ignacio Galdames,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 21:25:26

Ten fragment kodu zwróci wartość atrybutów danych np: data-id, data-time, data-name itd.., Pokazałem dla id

<a href="#" id="click-demo" data-id="a1">Click</a>

Js:

$(this).data("id");

/ / get the value of the data-id - > a1

$(this).data("id", "a2");

// spowoduje to zmianę Danych-id - > a2

$(this).data("id");

/ / get the value of the data-id - > a2

 1
Author: Arthi Rajgopal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-26 14:49:03