在jquery中复制特定的html代码
Duplicate a specific html code in jquery
我有一个表,里面有一些复杂的值(我的意思是,我必须发出几个请求才能得到我想要的所有值)。我需要在这个表的末尾添加行,并用与现有html代码相同的代码填充单元格。
例如,我有这样的东西:
<table id="table_cultures">
<tr>
<td>Just a string</td>
<td>Dropdown</td>
<td><div class='foo'> something..</div></td>
</tr>
</table>
<button id="plus_button" onclick="addRow()">+</button>
现在,在我的javascript中,我有这样的东西:
function addRow(){
var table = document.getElementById("table_cultures"); //Get the table element
var itk = document.getElementById('foo'); //Try to get the html to duplicate
var row = table.insertRow(-1); //Add in the end of the table
var c1 = row.insertCell(0);
var c2 = row.insertCell(1);
var c3 = row.insertCell(2);
c1.innerHTML= 'Culture';
c2.innerHTML='test';
c3.innerHTML=itk;
}
因此,在变量itk中,我试图生成html并将其拉入单元格,bu[Object]t它只显示HTMLFormElement
(因为这是一个我想要复制的表)。
这样做可能吗?或者还有其他更简单的方法吗?
您应该考虑克隆行节点,而不是通过以下方式获取和设置innerHTML:
var table = document.getElementById("table_cultures"); //Get the table element
var row = document.getElementById("rowTobeCloned"); //clone the required row
var clone = row.cloneNode(true); // copy child nodes too
table.appendChild(clone); // append the new row to the end of the table
目前您根本没有在代码中使用jQuery,但如果您正在寻找jQuery解决方案,您应该尝试.clone()
$("#table_cultures td:last").clone().appendTo("#table_cultures tr");
JSFiddle
您使用的是class("class='o'")而不是Id("getElementById")所以应该是像这个
function addRow(){...
var itk = document.getElementsByClassName('foo')[0]; //Try to get the html to duplicate
...}
相关文章:
- 如何解析结构不良的 html 代码
- 我的html表单无法验证.请参阅代码片段中的html代码和java脚本
- 将第一个字母大写并去掉html代码
- 我在下拉列表中尝试了下一个和前五年的html代码.接下来的5年我都过得很好.我怎样才能拿到之前的5年
- 使用.format在一些HTML代码中插入文本,会出现错误(Python)
- html代码没有在记事本++上运行
- 来自mysql的动态值用于html代码点火器视图中的图形
- 如何:编写漂亮的HTML代码和Javascript控制台
- 我需要java代码来打开html代码onclick事件
- html代码需要可点击的文本按钮
- 是否可以在JavaScript中包含HTML代码
- 如果javascript打开/关闭,则隐藏和显示html代码
- 使用PartialView作为带有变量的可重悬浮html代码
- 在jquery中复制特定的html代码
- 如何在AngularJS的上下文中使用Google Chrome Developer Tool在HTML代码中设置断点
- 显示HTML代码块
- 从HTML代码中提取数据
- 如何获取保存在变量中的HTML代码的任何属性的值
- 将html代码转换为十六进制
- JavaScript和Html代码来运行所有类型的视频并获取状态