我有一个div
标记如下:
<div id="DataEntryForm" style="position:absolute; left:100px;top:175px;width:350px; z-index:2;background-color:yellow; visibility:hidden;border-top-color: black;">
<table id="DataEntryFormTable" style=" width:100%" style="margin-top: -50px;">
<tr><td> Build Name</td><td> <input type="text" id="BuildName" name="BuildName" value="" /></td></tr>
<tr><td> Build Description</td><td> <input type="text" id="BuildDesc" name="BuildDesc" value="" /></td></tr>
<tr><td> Software Details</td><td> <input type="text" id="SoftwareDetail" name="SoftwareDetail" value="" /> </td></tr>
<tr><td> Hardware Details</td><td> <input type="text" id="HardwareDetail" name="HardwareDetail" value="" /> </td></tr><br>
<tr><td> </td></tr>
<tr>
<td>
<input type="button" value="Save" onclick="saveRecord()" /></td>
<td> <input type="button" value="Cancel" onclick="cancelOperation()"/></td>
</tr>
<br>
</table>
</div>
我想将数据库中的值加载到输入类型文本。所以,我需要获取每个节点的id,以便与我的json值和节点id匹配,并为其赋值。我正在尝试以下方法来实现这一目标。但是,我无法获得id值。任何人,请帮我解决这个问题。谢谢..
var nodes = deform.childNodes;
index =0;
// Load the first record in the collection.
// It is expected to have only one object in JS Object collection
var dbRecord= dbRecords[0];
while (index < nodes.length)
{
if(nodes[index].type=="text")
{
nodes[index].value = dbRecord[nodes[index].id];
}
index++;
}
答案 0 :(得分:1)
id
是正确的属性。问题是您没有检索您尝试从表中检索的节点。使用.children()或.childNodes()只能获取元素的直接子元素,因此您需要深入到表格中以访问您尝试填充的文本输入。或者,如果你想使用jQuery,一个选择器可以做到这一点:
$("#DataEntryFormTable input[type='text']")
如果你不使用jQuery,我会递归地使用.children()来找到你正在寻找的元素。
编辑:另外,确保在调用函数时包含括号,所以
var nodes = deform.childNodes;
将会
var nodes = deform.childNodes();
再次编辑: ...我没有看到您提供的数据。由于您在JSON数据中拥有所需的ID,因此可以使用这些ID直接查找元素。试试这个:
dbRecord= [{"HardwareDetail":"[B","BuildDesc":"Testing1","BuildID":"BL002","BuildName":"Second Name","SoftwareDetail":"ss"}];
record = dbRecord[0];
for (attr in record){
el = document.getElementById(attr);
if (el)
document.getElementById(attr).value = record[attr];
else
console.debug('no HTML element with ID ' + attr);
}
我认为console.debug
在某些浏览器中不起作用(IE?),所以当你完成测试时,你会想要把它拿掉。