2012-10-03 59 views
1

我正在構建一個使用dojo的配置對話框,以後我需要詢問用戶輸入。對話框中有多行,每行都有相同的格式和標籤。這裏是我用來構建每一行的html。獲取dojo的值NodeList內部元素

html = '<div class="cfgtxtrow"> <label>Label:</label> 
<input id="mac" type="hidden" name="mac" value="'+mac+'"/> 
<input id="label" type="text" maxlength="6" name="label" value="'+labl+'"/> 
</div>'; 

這部分的所有作品,我可以看到在Firebug返回數據。

我需要解析這些值並最終使用xhr將它們發送到服務器。所以我認爲我可以使用dojo查詢來獲取節點列表並遍歷每個節點以獲取輸入值並構建要發送的關聯數組。我認爲這很像通過編程驗證值。 (使用dojo.query(「。cfgtxtrow」)。forEach(function(node)),但無法弄清楚如何以編程方式(使用dojo)獲取每個節點上的值。我認爲我可以使用dojo.byId或查詢Node列表來獲取其內部元素,但我只是得到錯誤回來。

我開始懷疑我的概念都是錯誤的,因爲我認爲這將簡單。

這裏是我結束了..

dojo.query(".cfgtxtrow input").forEach(function(node) 
{ 
    id = dojo.attr(node, "id"); 
    console.debug(node); 

    if(id == "mac") mac = dojo.attr(node, "value"); // since mac comes first this is safe.. 
    if(id == "label") 
    { 
     labl = dojo.attr(node, "value"); 
     console.debug(mac); 
     console.debug(labl); 
     macLabels[mac] = labl; 
    } 
}); 
console.debug(macLabels[mac]); 
// send the data via the xhrPut call.. 

我認爲它應該是簡單的,dojo.attr調用似乎做的工作..

有沒有更好的方式來做同樣的事情?

回答

0

首先,您不應該使用id屬性來標識多行。在html文檔中只能有一個具有特定id的dom節點。也許這是你的問題的開始?

所以,如果你改變你的HTML如下:

<div class="cfgtxtrow"> <label>Label:</label> 
<input class="mac" type="hidden" name="mac" value="macValue"/> 
<input class="label" type="text" maxlength="6" name="label" value="labelValue"/> 
</div>​ 

在其上運行此(快速&髒)代碼

​require(['dojo/query'],function(query) { 
    var macLabels = {}; 
    query('.cfgtxtrow').forEach(function(row) { 
     var mac = query('.mac', row)[0].value; 
     var label = query('.label', row)[0].value; 
     macLabels[mac] = label; 
    }); 
    console.log(macLabels); 
});​​​​​​​​​ 

將輸出這個對象上的控制檯日誌:{macValue:「 labelValue「}