如何使用jQuery将HTML数据值作为字符串获取? [英] How can I get a HTML data value as a string with jQuery?

查看:74
本文介绍了如何使用jQuery将HTML数据值作为字符串获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在源HTML中有以下内容:

I have the following in my source HTML:

<li><a href="#" data-value="01">Test</a></li>

我想获取数据属性的值,因此我使用以下内容:

I want to get the value of the data attribute so I am using the following:

var abc = $(this).data('value');

这样可行但是如果有前导零则不行。例如,上面的
将值1放入abc。

This works okay BUT not if there is a leading zero. For example the above placed the value "1" into abc.

我有没有办法让它不将01转换为1?

Is there a way that I can get it not to convert the "01" into "1" ?

推荐答案

this.dataset.value;

// Or old school
this.getAttribute('data-value');

const a = document.querySelector("a");
console.log('Using getAttribute, old school: ', a.getAttribute('data-value'));
console.log('Using dataset, conforms to data attributes: ', a.dataset.value);

<ul>
  <li><a href="#" data-value="01">Test</a></li>
</ul>

感谢@MaksymMelnyk提出的数据集

Thanks to @MaksymMelnyk for the heads up on dataset

这篇关于如何使用jQuery将HTML数据值作为字符串获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆