I am a javascript learner. I have a little script that is almost finished. I just want to put DIV's around the html select attribute. If I do that, my script won't work. Why? Is this forbidden?
http://jsfiddle.net/triggerload/XHWwg/159/
<div id="test">
&l开发者_运维百科t;select class="valueList" name="n1">
<option selected value="0"></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
The problem almost certainly has to do with the way you are trying to grab the select
element:
function grabFormSelects(parent, class_name)
{
//make new array to hold nodes
var nodes = [];
for(var i=0;i<parent.childNodes.length;i++)
{
var node = parent.childNodes[i];
//filter out any node that isn't an element node and doesn't have the class name we're looking for
if(node.nodeType === 1 && node.className === class_name)
{
nodes.push(node);
}
}
return nodes;
}
You're checking only for direct child nodes of question_holder
, but when you add your div
the select
element is no longer a direct child of question_holder
, it is a child of the div
that you added. So of course it does not get returned by your grabFormSelect()
code.
As a quick fix, you can try:
function isDescendent(node, parent) {
//see if any of the nodes ancestors match the specified parent node
while (node.parentNode && node.parentNode != parent) {
node = node.parentNode;
}
return node.parentNode == parent;
}
function grabFormSelects(parent, class_name)
{
//make new array to hold nodes
var nodes = [];
var selects = document.getElementsByTagName("select");
for(var i=0;i<selects.length;i++)
{
var node = selects[i];
//filter out any node that isn't an element node and doesn't have the class name we're looking for
if(node.nodeType === 1 && node.className === class_name && isDescendent(node, parent))
{
nodes.push(node);
}
}
return nodes;
}
I think that it is because parent is no longer question_holder. It is now the id of the div.
function addListeners()
{
var holder = document.getElementById("question_holder");
var selects = grabFormSelects(holder, "valueList");
var holder2 = document.getElementById("question_holder2");
var selects2 = grabFormSelects(holder2, "valueList2");
for(var i=0;i<selects.length;i++)
{
selects[i].onchange = checkTarget;
}
for(var i=0;i<selects2.length;i++)
{
selects2[i].onchange = checkTarget2;
}
}
function grabFormSelects(parent, class_name)
{
//make new a
So holder should now call document.getElementById("test")
精彩评论