我'm using the jQuery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute? I'm使用 .on()
方法重新绑定已排序项的click事件 .
$("#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>
11 回答
要获取属性
data-id
的内容(如在<a data-id="123">link</a>
中),您必须使用或.data()(如果您使用较新的jQuery> = 1.4.3)
and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.
使用jQuery:
如果你不关心旧的IE浏览器,你也可以使用HTML5 dataset API
HTML
JS
演示:http://html5demos.com/dataset
完整浏览器支持列表:http://caniuse.com/#feat=dataset
重要的提示 . 请记住,如果您通过JavaScript动态调整
data-
attribute ,它将不会反映在data()
jQuery函数中 . 您还必须通过data()
函数进行调整 .JS:
HTML
JS
要么
适合我!
惊讶没人提到:
这是工作示例:https://jsfiddle.net/ed5axgvk/1/
这段代码将返回数据属性的值,例如:data-id,data-time,data-name等 . ,我已经为id显示了
JS:
//获取data-id - > a1的值
//这将改变data-id - > a2
//获取data-id - > a2的值
适合我!
使用自己的
id
访问数据属性对我来说有点容易 .$("#Id").data("attribute");
如果我们想使用现有的原生 JavaScript 来检索或更新这些属性,那么我们可以使用getAttribute和setAttribute方法来实现,如下所示:
Through JavaScript
Through jQuery
Read this documentation
我用$ .data - http://api.jquery.com/jquery.data/