我有一个简单的html页面来测试自定义“数据”属性,该属性用于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>

最佳答案

使用.attr('data-id'):

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


codepen

10-07 14:20
查看更多