使用 jQuery 检索 HTML 数据属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9720742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:11:39  来源:igfitidea点击:

Retrieving HTML data-attributes using jQuery

jqueryhtml

提问by Morais

How can I get the values stored in the data attributes using jQuery ?

如何使用 jQuery 获取存储在数据属性中的值?

<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" >

回答by Alytrem

Use the jQuery .data()function:

使用 jQuery.data()函数:

var speed = $("yourdiv").data("ts-speed");

回答by Marcus Blomberg

You should be able to use the .attr function:

您应该能够使用 .attr 函数:

var speed = $("yourdiv").attr("data-ts-speed");

回答by Frederiek

this shoud give you a idea how

这应该给你一个想法

html:

html:

<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" > </div>

js:

js:

$(document).ready(function(){
    var speed = $("div.sm-tot").data("ts-speed");
    var interval = $("div.sm-tot").data("ts-interval");
    $("div.sm-tot").append("speed: " + speed + "<br />");
    $("div.sm-tot").append("interval: " + interval + "<br />");

});

回答by Carlos Alberto Blanco Vivas

<div class="sm-tot" data-ts-speed="500" data-ts-interval="4000" data-ts-newVal="5000" >

well, for this div u can get someone attr with jquery using code like this first follow this pattern

好吧,对于这个 div,你可以使用这样的代码通过 jquery 获得某人的 attr,首先遵循此模式

   if is Class $(".ClassName").attr('AttrName');
   if is Id  $('#IDname').attr('attrName')

if u wan get "data-ts-interval" u will use $('.sm-tot').attr("data-ts-interval");

如果你想得到“data-ts-interval”,你将使用 $('.sm-tot').attr("data-ts-interval");