javascript - 当列有输入字段时,将 Html Table 转换为 Json,l输入文本或选择

标签 javascript jquery html json dynamic

How to convert HTML table to Javascript Object with jQuery

这个问题的延伸。 我的表格是动态的,它的单元格具有 Html 内容,例如用于输入描述的输入和用于下拉选择的选择。

因此,为了将该 html 内容获取到 json 对象,创建了这个已回答的问题。

最佳答案

只需更改代码即可:

//
// for each table row in table body
//
var tbl = $('#students tbody tr').map(function (idxRow, ele) {
    //
    // start building the retVal object
    //
    var retVal = {id: ++idxRow};
    //
    // for each cell
    //
    var $td = $(ele).find('td').map(function (idxCell, ele) {
        var input = $(ele).find(':input');
        //
        // if cell contains an input or select....
        //
        if (input.length == 1) {
            var attr = $('#students thead tr th').eq(idxCell).text();
            retVal[attr] = input.val();
        } else {
            var attr = $('#students thead tr th').eq(idxCell).text();
            retVal[attr] = $(ele).text();
        }
    });
    return retVal;
}).get();

console.log(tbl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="students" border="1">
    <thead>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Grade</th>
    </tr>
    </thead>
    <tbody>
    <tr class="student">
        <td>Oscar</td>
        <td><select>
            <option value="21">21</option>
            <option value="23" selected>23</option>
            <option value="32">32</option>
        </select></td>
        <td><input type="text" value="16.5"></td>
    </tr>
    <tr class="student">
        <td>Antonio</td>
        <td><select>
            <option value="21">19</option>
            <option value="23">23</option>
            <option value="32" selected>32</option>
        </select></td>
        <td><input type="text" value="14"></td>
    </tr>
    <tr class="student">
        <td>Jessica</td>
        <td><select>
            <option value="21" selected>21</option>
            <option value="23">23</option>
            <option value="32">32</option>
        </select></td>
        <td><input type="text" value="19"></td>
    </tr>
    </tbody>
</table>

关于javascript - 当列有输入字段时,将 Html Table 转换为 Json,l输入文本或选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313731/

相关文章:

javascript - 传单标记 addEventListener

javascript - 谷歌语音识别技术有API吗?

javascript - JS中如何让鼠标移开时文字消失?

php - 仅带css的样式列表,不带js等

html - @font-face 源中的相对 URL 不起作用

javascript - 如何访问 Node mssql中的输出参数?

javascript - 使用 ID 为段落内的字符串设置样式

javascript - 将具有子元素(包含 imgs/iframe)的元素绝对居中,同时在调整大小时保持其纵横比

javascript - 如何将变量插入jquery select属性 $ ("[myAttribute=' +myAttribute +']").html ('is working' );

html - 如何根据具体情况选择退出 CSS 样式?