JQuery,添加表行而不在Javascript中声明标记

JQuery, add table row without declaring the tags in Javascript

本文关键字:Javascript 声明 添加 JQuery      更新时间:2023-09-26

我想在HTML文档中准备一个表行作为模板,这样我就不会像以前那样在JS中键入它了。我只是将DOM元素保存为JQuery对象并进行了克隆,但在元素中进行克隆似乎并没有将其保存为对象。

我避免在JS:中声明

var _row = '<tr><td></td></tr>';

因为我想通过JS使元素成为动态的,而不是将其声明为字符串,所以我试图为表行创建一个HTML模板。

在HTML:中

<tr id='sampleRow'></tr>

在JS中:

var _row = $('#sampleRow');

合并日志时,_row将给出init的结果,而不是对象。

我怎么可能做到这样?

在HTML:中

<div class='sampleDiv'></div>

在JS中:

var _container = $('.sampleDiv').clone();

其中它是一个对象。

我刚刚找到了我的解决方案

我没有使用作为表行模板的容器,在该模板中,当您通过JQuery调用它并克隆它并将其附加到表时,不会发生任何事情,而是使用表作为容器。

在HTML:中

<table class="destTable">
</table>
<table class="tableRowTmp" hidden>
    <tr><td colspan="6">Sample</td></tr>
</table>

在JS中:

var oBannerTable = $('.destTable');
var oRow = $('.tableRowTmp').find('tr').clone();
oBannerTable.append(oRow.show());

我个人更喜欢通过像这样的jQuery在javascript中声明这样的简单对象

$("<tr />", {  text: 'Table Row txt',
               class: 'some class',
               id: 'elementid'
             }).appendTo("tbody");

如果你想把元素添加到tr中,你可以把它链接起来,也可以使用append,这看起来像

$("<tr />", {  text: 'Table Row txt',
               class: 'some class',
               id: 'elementid'
             }).append($('<div />', {
               text: 'Some text inside the div',
               class: 'anotherclass'
             })).appendTo("tbody");

这将使

<tr class='some class' id='elementid'>Table Row txt
  <div class='anotherclass'>Some Text inside the div</div> 
<tr/>

如果你想使用html作为模板,我建议使用John Resig建议的方法

http://ejohn.org/blog/javascript-micro-templating/

所以你可以做

<script type='companyname/mytemplate' id='trTemplate'>
 <tr id='sampleRow'></tr>
</script>
var template = $($("#trTemplate").innerHtml());