Jquery insertAfter html element refactor
My brain is fried after a long day and was given a task this weekend of inserting a table in our UI using jquery.
I've got some big ugly lines of code that are inserting html elements... wanted to see if there was a simple way to make this cleaner. I know I can break it into several lines, but there has to be a best practice开发者_运维问答:
$('#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;
});
Actually, you could just put the entire table as a string into a variable, and use 1 insertAfter();
to put it into the DOM.
I think it's wise to use as few of these calls as possible (append()
, prepend()
, insertAfter()
etc), since they're not cheap performance wise.
Place the HTML code inside your HTML document:
<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>
Hide it with CSS:
div.tiersTables { display:none; }
Then, on click, show it:
$('#submitNewTiers')click(function() {
$('.tiersTables').show();
});
精彩评论