我正在使用jQuery Quicksand插件。我需要得到点击项目的数据id,并将其传递给一个webservice。

如何获得data-id属性?我正在使用.on()方法重新绑定排序项的单击事件。

$("#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>


当前回答

我使用$.data:

//Set value 7 to data-id
$.data(this, 'id', 7);

//Get value from data-id
alert( $(this).data("id") ); // => outputs 7

其他回答

如果你不担心旧的ie浏览器,你也可以使用HTML5数据集API。

HTML

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

JavaScript

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

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

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

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

重要的注意。请记住,如果您通过JavaScript动态调整data-属性,它将不会反映在data() jQuery函数中。你还必须通过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

我有一个跨度。我想获取属性data-txt-lang的值,该值是使用定义的。

$(document).ready(function ()
{
    <span class="txt-lang-btn" data-txt-lang="en">EN</span>
    alert($('.txt-lang-btn').attr('data-txt-lang'));
});

要获得属性data-id的内容(如<a data-id="123">link</a>),您必须使用

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

或.data()(如果您使用更新的jQuery >= 1.4.3)

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

data-后面的部分必须小写,例如data-idnum不行,但data-idnum可以。

对于纯js

 let btn = document.querySelector('.your-btn-class');
 btn.addEventListener('click',function(){
 console.log(this.getAttribute('data-id'));
 })