如何获取Node的id名称?

时间:2011-03-18 04:08:38

标签: javascript json dom

我有一个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>&nbsp;Build Name</td><td> <input type="text" id="BuildName" name="BuildName" value="" /></td></tr>
        <tr><td>&nbsp;Build Description</td><td> <input type="text" id="BuildDesc" name="BuildDesc" value="" /></td></tr>
        <tr><td>&nbsp;Software Details</td><td> <input type="text" id="SoftwareDetail" name="SoftwareDetail" value="" /> </td></tr>
        <tr><td>&nbsp;Hardware Details</td><td> <input type="text" id="HardwareDetail" name="HardwareDetail" value="" /> </td></tr><br>
        <tr><td>&nbsp;</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++;
}

1 个答案:

答案 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":"Se­cond 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?),所以当你完成测试时,你会想要把它拿掉。