【问题标题】:Jquery insertAfter html element refactorJquery insertAfter html元素重构
【发布时间】:2011-06-24 23:35:15
【问题描述】:

经过漫长的一天后,我的大脑被煎炸了,本周末被分配了一项任务,即使用 jquery 在我们的 UI 中插入一个表格。

我有一些插入 html 元素的大而丑陋的代码行......想看看是否有一种简单的方法可以使这个更清洁。我知道我可以把它分成几行,但必须有一个最佳实践:



    $('#submitNewTiers').bind('click',function (e) {

    $('<div class="tiersTables"><span><a href="" rel="#overlay">Edit Tiers </a></span><table class="visible" id="newTiersTable"><thead&gr;<tr><th>Range</th><th>List Price</th><th>Quote Price</th><th class="lastTh">Approval?</th></tr></thead></table></div>').insertAfter('div.tiersTables');
    $('<tbody><tr><td>HERE</td><td></td><td></td><td></td></tr></tbody>').insertAfter('#newTiersTable thead');
        return false;
    });

【问题讨论】:

    标签: jquery jquery-selectors clone insertafter


    【解决方案1】:

    其实,你可以把整个表格作为一个字符串放到一个变量中,然后用 1 insertAfter(); 把它放到 DOM 中。

    我认为明智的做法是尽可能少地使用这些调用(append()、prepend()、insertAfter() 等),因为它们的性能并不便宜。

    【讨论】:

    • 感谢您的提示,因为稍后我必须将动态值添加到 TD 中,这将需要进一步调用。但是,如果有附加值,我总是可以使用 $.each。
    【解决方案2】:

    将 HTML 代码放入您的 HTML 文档中:

    <div class="tiersTables">
        <span>
            <a href="" rel="#overlay">Edit Tiers </a>
        </span>
        <table class="visible" id="newTiersTable">
            <thead>
                <tr>
                    <th>Range</th>
                    <th>List Price</th>
                    <th>Quote Price</th>
                    <th class="lastTh">Approval?</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>HERE</td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
    

    用 CSS 隐藏它:

    div.tiersTables { display:none; }
    

    然后,在点击时显示它:

    $('#submitNewTiers')click(function() {
        $('.tiersTables').show();
    });
    

    【讨论】:

    • 如果我只添加一个表,我喜欢这个答案,但是我需要能够增加我显示的表的数量。因此,使用您的建议,我将不得不创建多个 html 表并隐藏它们,然后在点击时显示最近的表。
    • @Robert 我的建议是:从一开始就有一个隐藏的表格(硬编码到您的 HTML 源代码中)。然后,每当您需要一个新表时,克隆它并将克隆附加到 DOM(在所需位置)。为此,jQuery 有一个方便的clone() method。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多