2013-04-26 30 views
1

我有一个简单的html页面来测试用于HTML复选框以保存'id'数据的自定义'数据'属性。但是,根据所选复选框检索这些'id'的值时,我在这些data-id属性中丢失了前导零。例如,一个特定的复选框被定义为:如何保持使用自定义“数据”属性的前导零

<input type="checkbox" data-id="00372" > 

当我检索它的“身份证”的值,返回值是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

您是否希望所有属性具有一致的长度?这个长度是灵活的还是静态的(即5位数字)? – oomlaut 2013-04-26 19:30:27

+0

如果您正在寻找简单地添加前导零,这已被回答:http://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript – oomlaut 2013-04-26 19:31:21

+0

长度data-id属性是任意的,可能有或者可能没有前导零。这些属性的数据实际上来自遗留数据库(虽然设计不好),但我在这里通过硬编码值来简化这些属性,以便读者在本论坛中看到它们。 – 2013-04-29 15:58:53

回答

4

使用.attr( '数据ID'):

function buttonCollectId_Click() 
    {    
     $('input[type=checkbox]:checked').each(function(index,value){ 
       console.log('Selected:' + $(this).attr('data-id')); 
     }); 
    } 

codepen

+0

谢谢,您的解决方案正在运行。 – 2013-04-29 15:49:39

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- * - 属性

+0

感谢您的信息。 – 2013-04-29 15:50:28

相关问题