如何使用 JavaScript 在单击按钮时覆盖动态创建的表的行值
how to overwrite the row values of dynamically created table on button click using javascript
我有一个下拉菜单,用户可以从中选择"旧","新"等选项。根据所选选项,我正在从xml查询数据并将其显示在表中。
目录
<body>
<table id="NovelList" class="NovelList" border="1">
<tr>
<th>Novel Title</th>
<th>Author</th>
<th>Publishing Year</th>
<th>Price</th>
<th>Purchase</th>
</tr>
</table>
</body>
为了将数据添加到表中的选项选择我正在这样做:-
var nodes = xmlDoc.evaluate(pathExpr, xmlDoc, nsResolver, XPathResult.ANY_TYPE, null);
var result = nodes.iterateNext();
while (result) {
var b= [];
var d=result.childNodes;
for(var i=0;i<d.length;i++){
if(d[i].nodeType == 1){
b.push(d[i]);
}
}
for(var p=0;p<b.length;p++){
var n = b[p];
if (n.localName== "title"){var t = n.childNodes[0].nodeValue;}
if (n.localName== "author"){var a = n.childNodes[0].nodeValue;}
if (n.localName== "year"){var y = n.childNodes[0].nodeValue;}
if (n.localName== "price"){var pr = n.childNodes[0].nodeValue;}
if (n.localName== "code"){var c = n.childNodes[0].nodeValue;}
}
$('.NovelList tr:last').after(
'<tr><td class="value">'+ t
+ '</td><td class="value">'+ a
+ '</td><td class="value">' + y
+ '</td><td class="value">' + pr
+ '</td><td class="chk"><input type="checkbox" name="chkbox" value='+'"'+c+'"'+'></td></tr>');
result = nodes.iterateNext();
}
}
但是当我使用".after"时,每次我选择一个选项时,它都会附加到已经显示的表中。
每当选择选项时,我想替换表格行。
首先,像这样分开你的头部和身体:
<table>
<thead>
<tr>...</tr>
</thead>
<tbody>
<tr>...</tr>
</tbody>
</table>
然后致电
$('tbody').empty();
这应该可以解决问题。基本上,您需要先擦除 DOM。
感谢Fenixp的帮助。我在表格中添加了标题和正文标签,但随后 empty() 不起作用,所以我最终使用了 remove()。
编辑后的 HTML 文件
<table id="NovelList" class="NovelList" border="1">
<thead>
<tr>
<th>Novel Title</th>
<th>Author</th>
<th>Publishing Year</th>
<th>Price</th>
<th>Purchase</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
在添加行之前调用它-
$('#NovelList tbody >tr.dtr').remove();
并添加行使用
$('.NovelList tbody tr:last').after(
'<tr class="dtr"><td class="value">'+ t[0].firstChild.nodeValue
+ '</td><td class="value">'+ a[0].firstChild.nodeValue
+ '</td><td class="value">' + y[0].firstChild.nodeValue
+ '</td><td class="value">' + p[0].firstChild.nodeValue
+ '</td><td class="chk"><input type="checkbox" name="chkbox" value='+'"'+code+'"'+'></td></tr>');
相关文章:
- 如何在javascript中创建动态json对象
- 如何创建动态ajax提交表单
- 如何在javascript中创建动态正则表达式
- 如何使用pouchdb创建动态查询(couchdb可能也是如此)
- 如何在jquery mobile中使用json文件创建动态下拉菜单
- 基于所选下拉列表值创建动态复选框
- 使用推动创建动态对象
- 在浏览器窗口中创建动态灵活的分割标记
- 将字符串与integer连接,用作jquery中的变量(创建动态变量)
- 创建动态javascript对象
- 如何使用指令属性值创建动态模板
- 使用 JavaScript 创建动态下拉列表
- 如何在创建动态 HTML 页面时使用日期选择器
- 使用javascript中的append创建动态下拉列表
- Jquery - 创建动态名称选择器
- 如何根据查询字符串值创建动态超链接
- 使用javascript创建动态多维关联数组
- 使用javascript创建动态二级下拉列表
- 在JavaScript中创建动态绑定
- 在JS中创建动态对象