繁体   English   中英

使用td标签中的value字段作为html表中的隐藏字段

[英]Using value field in td tag as hidden field in html table

我需要在HTML表中存储一些链接到单元格的数据。

有什么理由使用td标签中的value属性? 有没有更好的方法可以做到这一点?

https://jsfiddle.net/uj36cxoL/1/

<table width="100%" border="0">
  <tr>
    <td id="c00">00</td>
    <td id="c01">01</td>
    <td id="c02">02</td>
  </tr>
  <tr>
    <td id="c10">10</td>  
    <td id="c11">11</td>
    <td id="c12">12</td>
  </tr>
</table>
Col:
<select id="col">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
Row:
<select id="row">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<button id="getValue">Get value</button>
<script>
document.getElementById( "getValue" ).onclick = function()
{
    var col = document.getElementById( "col" ).value;
    var row = document.getElementById( "row" ).value;
    var cellId = "c" + col + row; //generate id of cell (e.g. c01)
    var cell = document.getElementById( cellId );
    alert( "The value of cell c" + col + row + "is: " + cell.value );
};
</script>

<script>
var count = 1;
for( var col = 0; col < 3; col++ )
{
    for( var row = 0; row < 6; row++ )
    {
        var cellId = "c" + col + row; //generate id of cell (e.g. c01)
        var cell = document.getElementById( cellId );
        cell.value = count++;
        cell.innerHTML = cell.innerHTML + " (value = " + cell.value + ")";
    }
}
</script>

我已经在Windows的IE,FF,Chrome和Opera中对其进行了测试,它似乎可以正常工作。 它不必在移动设备上工作。

HTML5能够执行这种带有数据属性的操作 它们允许您通过访问所涉及的DOM元素的.dataset.myData属性,将所需的任何数据存储在任何HTML标记中,以便以后根据需要访问它们。 (对于您来说,这将是cell.dataset.whatever。)尽管您现在拥有的东西可能会工作,但由于它不是HTML5的正式标准,因此它也随时可能停止工作。 关于数据属性的MDN页面非常好: https : //developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

顺便说一句,数据属性确实可以与JQuery一起使用,但是就像您可以使用JQuery进行的大多数操作一样,您也可以使用常规JS来进行处理,而不必加载整个JQuery库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM