有条件地生成表行中断 [英] Generate table row break conditionally

查看:66
本文介绍了有条件地生成表行中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a <table> with two cells that I want to display horizontally if device is computer or vertically if it's mobile. I borrowed a JS function to detect mobile from this answer https://stackoverflow.com/a/11381730/3298930 that works great.

我的水平表看起来像这样(实际上,它更复杂,但是我想简化一下):

My horizontal table looks like this (actually, it's more complicated, but I want to make it simple) :

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

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

In order to make it vertical I only need to insert two tags :

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

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

My question is : how can I insert those two tags by calling a JS function? I wish I could do something like this :

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

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

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

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

mobile() is the JS function that returns TRUE if device is mobile.

我找到了两个有关操作DOM的答案( https://stackoverflow.com/a/18333557/3298930 https://stackoverflow.com/a/27525472/3298930 ),但我无法使其正常运行,在这里:

I found two answers about manipulating the DOM (https://stackoverflow.com/a/18333557/3298930 and https://stackoverflow.com/a/27525472/3298930) but I couldn't make it work, here it is :

<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>

推荐答案

如果只想在初始加载时执行

If you want to do only on initial load

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>

这篇关于有条件地生成表行中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆