【问题标题】:Generate table row break conditionally有条件地生成表格换行符
【发布时间】:2020-08-01 01:13:16
【问题描述】:

我有一个带有两个单元格的<table>,如果设备是计算机,我想水平显示,如果是移动设备,我想垂直显示。我借用了一个 JS 函数来从这个答案https://stackoverflow.com/a/11381730/3298930 中检测手机,效果很好。

我的横桌是这样的(其实比较复杂,不过我想简单点):

<table>
  <tr>
    <td> <video>s </td>
    <td> description and capture data </td>
  </tr>
</table>

为了让它垂直,我只需要插入两个标签:

<table>
  <tr>
    <td> <video>s </td>
  </tr> ◄────────────────────────────┐
  <tr>  ◄────────────────────────────┘
    <td> description and capture data </td>
  </tr>
</table>

我的问题是:如何通过调用 JS 函数插入这两个标签?我希望我能做这样的事情:

<table>
  <tr>
    <td> <video>s </td>

<script>
if ( mobile() ) write "</tr>
                       <tr>";
</script>

    <td> description and capture data </td>
  </tr>
</table>

mobile() 是 JS 函数,如果设备是移动设备,则返回 TRUE。

我找到了两个关于操作 DOM 的答案(https://stackoverflow.com/a/18333557/3298930https://stackoverflow.com/a/27525472/3298930),但我无法让它工作,这里是:

<table>
  <tr>
    <td id="my_td"> <video>s </td>

<script>
if ( mobile() ) $("#my_td").append("</tr><tr>");
</script>

    <td> description and capture data </td>
  </tr>
</table>

【问题讨论】:

标签: javascript html html-table


【解决方案1】:

如果你只想在初始加载时做

function isMobile() {
    return true; // or false
}

$(function () {

    if (isMobile()) {
        $td = $('#tbl').find('#row1_item2').detach();
        $a = $('#row1').after(`<tr id="row2"></tr>`);

        $('#row2').append($td);
    }

    $('#row1_item2').css('display', 'table-row');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table id="tbl">
    <tr id="row1">
        <td id="row1_item1">a</td>
        <td id="row1_item2" style="display: none;">b</td>
    </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 2021-10-07
    • 2022-01-15
    • 2018-05-05
    • 2012-03-09
    相关资源
    最近更新 更多