如何获取data-id属性?

本文翻译自:How to get the data-id attribute?

I'm using the jQuery quicksand plugin. 我正在使用jQuery quicksand插件。 I need to get the data-id of the clicked item and pass it to a webservice. 我需要获取所单击项的data-id并将其传递给webservice。 How do I get the data-id attribute? 如何获取data-id属性? I'm using the .on() method to re-bind the click event for sorted items. 我正在使用.on()方法重新绑定已排序项的click事件。

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


#1楼

参考:https://stackoom.com/question/MHLy/如何获取data-id属性


#2楼

If we want to retrieve or update these attributes using existing, native JavaScript , then we can do so using the getAttribute and setAttribute methods as shown below: 如果我们想使用现有的原生JavaScript检索或更新这些属性,那么我们可以使用getAttribute和setAttribute方法来实现,如下所示:

Through JavaScript 通过JavaScript

Through jQuery 通过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');

Read this documentation 阅读此文档


#3楼

I use $.data - http://api.jquery.com/jquery.data/ 我使用$ .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

#4楼

If you are not concerned about old IE browsers, you can also use HTML5 dataset API 如果您不关心旧的IE浏览器,也可以使用HTML5数据集API

HTML HTML

My Awesome Div

JS JS

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

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

Demo: http://html5demos.com/dataset 演示: http : //html5demos.com/dataset

Full browser support list: http://caniuse.com/#feat=dataset 完整的浏览器支持列表: http : //caniuse.com/#feat=dataset


#5楼

var id = $(this).dataset.id

适合我!


#6楼

Important note. 重要的提示。 Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will NOT be reflected in the data() jQuery function. 请记住,如果您通过JavaScript动态调整data- 属性 ,它将不会反映在data() jQuery函数中。 You have to adjust it via data() function as well. 您还必须通过data()函数进行调整。

link

js: 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

你可能感兴趣的:(如何获取data-id属性?)