2011-06-24 70 views
0

我的大脑在漫长的一天后被炸,本周末在我们的UI中使用jquery插入表的任务给了我一个任务。Jquery insertAfter html元素重构

我已经有一些插入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; 
    }); 

回答

1

其实,你可以只是把整个表作为一个字符串转换为变量,使用1 insertAfter();付诸DOM。

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

+0

我很欣赏你的小费因为稍后我必须在动态增加动态值,这将需要进一步调用。但是,如果有附加值,我总是可以使用$ .each。 – Robert

+0

@Robert考虑[模板](http://api.jquery.com/category/plugins/templates/) –

1

将您的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(); 
}); 
+0

我喜欢这个答案,如果我只是添加一个表,但我需要能够增加表的数量我显示。所以使用你的建议,我将不得不创建多个html表并隐藏它们,然后单击显示最近的表。 – Robert

+1

@Robert我的建议是这样的:从一开始就有一个隐藏表(硬编码到您的HTML源代码中)。然后,每当你需要一个新表时,克隆它并将该克隆追加到DOM(在所需位置)。为此,jQuery有一个方便的['clone()'方法](http://api.jquery.com/clone/)。 –