我有一个简单的html页面来测试自定义'data'属性,该属性用于HTML复选框以保存'id'数据。但是,在针对所选复选框检索那些“id”的值时,我在那些data-id属性中丢失了前导零。例如,一个特定的复选框定义为:
<input type="checkbox" data-id="00372" >
当我检索其'id'的值时,返回的值是372而不是00372.请帮助。
我的HTML页面的代码详细信息:
<html>
<head>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
function buttonCollectId_Click()
{
$('input[type=checkbox]:checked').each(function(index,value){
console.log('Selected:' + $(this).data('id'));
});
}
</script>
</head>
<body>
<table>
<tr>
<td>Employee Id:</td><td>02813</td><td><input type="checkbox" data-id="02813" ></td>
</tr>
<tr>
<td>Employee Id:</td><td>46522</td><td><input type="checkbox" data-id="46522" ></td>
</tr>
<tr>
<td>Employee Id:</td><td>00372</td><td><input type="checkbox" data-id="00372" ></td>
</tr>
<tr>
<td colspan="3"><input id="buttonCollectId" type="button" value="Collect Ids" onclick="buttonCollectId_Click();"></td>
</tr>
</table>
</body>
</html>
答案 0 :(得分:4)
使用.attr('data-id'):
function buttonCollectId_Click()
{
$('input[type=checkbox]:checked').each(function(index,value){
console.log('Selected:' + $(this).attr('data-id'));
});
}
答案 1 :(得分:1)
正如尼克建议的那样,如果你想要有问题的数据属性的字符串表示,你应该使用.attr()
方法。
由于jQuery文档状态(http://api.jquery.com/data/#data-key):
"Every attempt is made to convert the string to a JavaScript value
(this includes booleans, numbers, objects, arrays, and null) otherwise
it is left as a string. To retrieve the value's attribute as a string
without any attempt to convert it, use the attr() method."
.data()
方法用于存储与html元素关联的(或多或少)任意数据的序列化。它符合HTML5数据属性规范,可以在http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data- * - 属性