0
這兩個javascript函數可以在未改變的dom元素上完美工作。然而,當要求通過第二個函數刪除附加到dom的元素時,delete_route函數失敗。爲了清楚起見,我只查看parts[0]
總是選項的元素 - 它是通過在「_」上拆分a> id創建的。Javascript失敗,因爲dom已被修改?
爲什麼JavaScript顯然看到「本地」dom對象和插入的對象之間的這種區別?
//handle delete events
function delete_route (parts) {
if (parts[0] == "field") {
var select_container = "container_"+parts[2];
var getContainer = document.getElementById(select_container);
getContainer.parentNode.removeChild(getContainer);
} else if (parts[0] == "option") {
var optionId = parts[0]+"_"+parts[2]+"_"+parts[3];
var getOption = document.getElementById(optionId);
getOption.parentNode.removeChild(getOption);
}
}
//handle new events
function new_route (parts) {
var highest_number = -1;
if (parts[0] == "field") {
} else if (parts[0] == "option") {
var selectContainer = "container_"+parts[2];
var thisContainer = document.getElementById(selectContainer);
//get last option id (for new object tagging)
var optionList = thisContainer.getElementsByTagName("input");
var optionListLength = optionList.length -2;
//more accurate new node placement than last option which didn't work correctly anyway
lastChild = "options_wrapper_"+parts[2];
var lastChildNode = document.getElementById(lastChild);
//generate option
var labelNode = document.createElement ("label");
var inputNode = document.createElement ("input");
var linkNode = document.createElement ("a");
var breakNode = document.createElement ("br");
inputNode.setAttribute("type", "text");
var inputNodeId = parts[0]+"_"+parts[2]+"_"+optionListLength;
inputNode.setAttribute("id", inputNodeId);
inputNode.setAttribute("name", inputNodeId);
inputNode.setAttribute("value", "Undefined");
labelNode.setAttribute ("for", inputNodeId);
var labelNodeText = document.createTextNode ("Option Value");
linkNode.setAttribute("href", "#");
var linkId = parts[0]+"_delete_"+parts[2]+"_"+optionListLength;
linkNode.setAttribute("id", linkId);
var linkNodeText = document.createTextNode ("Delete option");
lastChildNode.appendChild (labelNode);
labelNode.appendChild (labelNodeText);
lastChildNode.appendChild (inputNode);
lastChildNode.appendChild (linkNode);
linkNode.appendChild (linkNodeText);
lastChildNode.appendChild (breakNode);
}
}
HTML適用於(我已經儘管一些努力與創造的一部分 - 選擇由JavaScript所插入的是完全張玉峯,以「本土」頁面元素):基於
<div id="options_wrapper_7">
<label for="option_7_0">Option Value</label><input type=text id="option_7_0" name="option_7_0" value="Red"> <a id="option_delete_7_0" href="#">Delete option</a><br>
<label for="option_7_1">Option Value</label><input type=text id="option_7_1" name="option_7_1" value="Green"><a id="option_delete_7_1" href="#">Delete option</a><br>
<label for="option_7_2">Option Value</label><input type=text id="option_7_2" name="option_7_2" value="Blue"><a id="option_delete_7_2" href="#">Delete option</a><br>
</div>
so插入新元素後調用該函數?無論如何會嘗試,但只是被叫走! – YsoL8 2011-02-12 17:55:31