如何在不导致 HTML 表格失真的情况下正确使用追加

How to use append correctly without causing HTML Table distortion

本文关键字:情况下 真的 追加 失真 表格 HTML      更新时间:2023-09-26

我有一个表,其中包含从MySQL数据库动态加载的链接行。

目前,为了让用户像使用命名锚点一样快速访问每个新字母的开头,我有以下脚本,它在动态创建锚点和 HTML 表的一小部分样本时工作得很好。 您可以从代码中看到,脚本不断将其添加到TD标签的前面,这导致表格失真。 JavaScript 新手,不确定我哪里出错了。 我在网上找到了这个剧本。

总而言之,我希望命名锚点在所有内容的前面的TD标签内部显示。

<script type='text/javascript'>//<![CDATA[ 
$(function(){
char = "";
$('.myTable').each(function(){
    td = $(this);
    $(this).child('td#front').each(function(){
        x = $(this).text()[0];
        if(x!=char){
            char = x;
            q = $('<div class="lettergroup" />').appendTo(td);
            $('<a name="'+char+'" />').appendTo(q);
            $('<h2>'+char+'</h2>').appendTo(q);
        }
        $(this).appendTo(q);
    });
});
$('.lettergroup').each(function(lgi){
    lg = $(this);
    c = $(this).child('td#front');
    l = c.length;
    h = Math.ceil(l/2);
    if(l>1){
        lc = $('<div class="lettercolumn" />').prepend(lg);
        c.each(function(si){
            if(si==h) lc = $('<div class="lettercolumn" />').appendTo(lg);
            $(this).prepend(lc);
        });
    $('<br class="clear" />').appendTo(lg);
    }
});

});//]]>  
</script>
<table class="myTable">
  <tr>
    <td>Text</td>
    <a class="letterAnchor" name="A"></a><td class="front">A Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
  </tr>
</table>

我需要的选项是 prependTo。

不带 To 的前缀本身不处理 HTML

有关更多详细信息,请参阅此页面。

http://www.w3schools.com/jquery/jquery_ref_html.asp