当之前有值时,如何修复createTextNode的值未定义?

时间:2014-03-06 21:46:38

标签: javascript html5 dom appendchild textnode

我正在努力解决如何存储/保存文本节点的值,这对解决我的问题至关重要。基本上,它解决了选择选项菜单。我逐行调试程序,发现函数onChange()完成后我回到onChange()函数来改变一个select选项,所有四个文本节点的值都是undefined并且没有保留我第一次.createTextNode时存储的先前值。奇怪的是,仍然存储了iterationCount。我这样做的原因是因为每次我更改选择选项时,createTextNode都会重复打印result。所以我这样做是为了避免这种情况发生:

if(iterationCount === undefined) // used on first launch
{
    iterationCount = 0; // set the value to 0
}

//iterationCount > 0 (on second or more tries), allow permission to remove the pNodes
if(iterationCount > 0)
{
    pNodeBudget.removeChild(pTextBudget);
    pNodeBrand.removeChild(pTextBrand);
    pNodeType.removeChild(pTextType);
    pNodeLens.removeChild(pTextLens);
    iteration--; // put it back to 0 right after removing the pNodes.
}

这段代码基本上就是我创建文本节点的地方:

// iteration Count == 0 (first try), allow create text node
if(iterationCount == 0)
{
    var pNodeBudget = document.createElement("p");
    var pNodeBrand = document.createElement("p");
    var pNodeType = document.createElement("p");
    var pNodeLens = document.createElement("p");

    var pTextBudget, pTextBrand, pTextType, pTextLens;
    pTextBudget = document.createTextNode("Your DSLR budget range selected was: " + budText);
    pTextBrand = document.createTextNode("The DSLR brand you selected was: " + brandText);
    pTextType = document.createTextNode("The type of photography you selected was: " + typeText);

    pTextLens = document.createTextNode("The type of lenses you selected was: " + lensText);                                

    // append text to paragraph
    pNodeBudget.appendChild(pTextBudget);
    pNodeBrand.appendChild(pTextBrand);
    pNodeType.appendChild(pTextType);
    pNodeLens.appendChild(pTextLens);
    // remove pNodes and append changes again
    // append to document page
    result.appendChild(pNodeBudget);
    result.appendChild(pNodeBrand);
    result.appendChild(pNodeType);
    result.appendChild(pNodeLens);
    resultForm = document.getElementById("resultForm").style.display = "block";
    iterationCount++; // 1 increment after one time, do something different
}

完整的JavaScript代码:

        var result;
        var budSel, budList, budText;
        var brandSel, brandList, brandText;
        var typeSel, typeList, typeText;
        var lensSel, lensList, lensText;
        var brandForm, typeForm, lensForm;
        var iterationCount;

        function DSLRinit()
        {
            // set Select value to Select one onload() page
            var setSelect = document.getElementById("budgetSel").selectedIndex = "0";
            setSelect = document.getElementById("brandSel").selectedIndex = "0";
            setSelect = document.getElementById("typeSel").selectedIndex = "0";
            setSelect = document.getElementById("lensSel").selectedIndex = "0";

            brandForm = document.getElementById("brandForm").style.display = "none";
            typeForm = document.getElementById("typeForm").style.display = "none";
            lensForm = document.getElementById("lensForm").style.display = "none";
            var resultForm = document.getElementById("resultForm").style.display = "none";

            // dynamically create the select options onload()

            budSel = document.getElementById("budgetSel");
            budSel.options[0] = new Option("Select One");
            budSel.options[1] = new Option("< $500");
            budSel.options[2] = new Option("< $1000");
            brandSel = document.getElementById("brandSel");
            brandSel.options[0] = new Option("Select One");
            brandSel.options[1] = new Option("Canon");
            brandSel.options[2] = new Option("Nikon");
            brandSel.options[3] = new Option("Sony");
            brandSel.options[4] = new Option("Pentax");
            typeSel = document.getElementById("typeSel");
            typeSel.options[0] = new Option("Select One");
            typeSel.options[1] = new Option("Wildlife");
            typeSel.options[2] = new Option("Aerial");
            typeSel.options[3] = new Option("Sports");
            typeSel.options[4] = new Option("Portrait");
            typeSel.options[5] = new Option("Architectural");
            typeSel.options[6] = new Option("Macro");
            lensSel = document.getElementById("lensSel");
            lensSel.options[0] = new Option("Select One");
            lensSel.options[1] = new Option("Normal \"Portrait\" Lens / 35-50mm");
            lensSel.options[2] = new Option("Telephoto Zoom Lens / > 200mm");
            lensSel.options[3] = new Option("Ultra-Wide Angle Lens / < 35mm");
        }

        // function to dynamically change user selected options
        function onChange()
        {
            result = document.getElementById("result"); // get the <form> element id

            budgetForm = document.getElementById("budgetForm").style.display = "block";



            budSel = document.getElementById("budgetSel"); // get the budget <select>
            budList = budSel.options.selectedIndex; // get the selected option index of budget select
            budText = budSel.options[budList].text; // get the text of the selected option of budget element

            if(budList == 1 || budList == 2)
            {
                // print the results into the result form


                //result.innerHTML = "<p>Your DSLR budget range selected was: " + budText + "</p>";
                //result.appendChild(result);

                brandForm = document.getElementById("brandForm").style.display = "block";
                //brandForm = document.getElementById("brandForm").style.margin = "-100px";

                brandSel = document.getElementById("brandSel"); // get the brand <select>
                brandList = brandSel.options.selectedIndex; // get the selected option index of brand select
                brandText = brandSel.options[brandList].text; // get the text of the selected option of brand element

                if(brandList == 1 || brandList == 2 || brandList == 3 || brandList == 4)
                {
                    // print the results into the result form
                    //result.innerHTML += "<p>The DSLR brand you selected was: " + brandText + "</p>";

                    typeForm = document.getElementById("typeForm").style.display = "block";

                    typeSel = document.getElementById("typeSel"); // get the type <select>
                    typeList = typeSel.options.selectedIndex; // get the selected option index of type select
                    typeText = typeSel.options[typeList].text; // get the text of the selected option of type element

                    if(typeList == 1 || typeList == 2 || typeList == 3 || typeList == 4 || typeList == 5 || typeList == 6 || typeList == 7)
                    {
                        // print the results into the result form
                        //result.innerHTML += "<p>The type of photography you selected was: " + typeText + "</p>";
                        //result.

                        lensForm = document.getElementById("lensForm").style.display = "block";

                        lensSel = document.getElementById("lensSel"); // get the lens <select>
                        lensList = lensSel.options.selectedIndex; // get the selected option index of lens select
                        lensText = lensSel.options[lensList].text; // get the text of the selected option of lens element

                        if(lensList == 1 || lensList == 2 || lensList == 3)
                        {
                            // print the results into the result form
                            //result.innerHTML += "<p>The type of lenses you selected was: " + lensText + "</p>";

                            // display the printed results
                            // create <p></p> node
                            //var pNodeBudget, pNodeBrand, pNode

                            //var linebreak = document.createElement("br");
                            // detect how many times changes were being made
                            if(iterationCount === undefined) // used on first launch
                            {
                                iterationCount = 0; // set the value to 0
                            }

                            //iterationCount > 0 (on second or more tries), allow permission to remove the pNodes
                            if(iterationCount > 0)
                            {
                                pNodeBudget.removeChild(pTextBudget);
                                pNodeBrand.removeChild(pTextBrand);
                                pNodeType.removeChild(pTextType);
                                pNodeLens.removeChild(pTextLens);
                                iteration--; // put it back to 0 right after removing the pNodes.
                            }
                            // iteration Count == 0 (first try), allow create text node
                            if(iterationCount == 0)
                            {
                                var pNodeBudget = document.createElement("p");
                                var pNodeBrand = document.createElement("p");
                                var pNodeType = document.createElement("p");
                                var pNodeLens = document.createElement("p");

                                var pTextBudget, pTextBrand, pTextType, pTextLens;
                                pTextBudget = document.createTextNode("Your DSLR budget range selected was: " + budText);
                                //linebreak.appendChild(pTextBudget);
                                pTextBrand = document.createTextNode("The DSLR brand you selected was: " + brandText);
                                //linebreak.appendChild(pTextBrand);
                                pTextType = document.createTextNode("The type of photography you selected was: " + typeText);
                                //linebreak.appendChild(pTextType);
                                pTextLens = document.createTextNode("The type of lenses you selected was: " + lensText);                                
                                //linebreak.appendChild(pTextLens);
                                // append text to paragraph
                                pNodeBudget.appendChild(pTextBudget);
                                pNodeBrand.appendChild(pTextBrand);
                                pNodeType.appendChild(pTextType);
                                pNodeLens.appendChild(pTextLens);
                                // remove pNodes and append changes again


                                // append to document page
                                result.appendChild(pNodeBudget);
                                result.appendChild(pNodeBrand);
                                result.appendChild(pNodeType);
                                result.appendChild(pNodeLens);
                                resultForm = document.getElementById("resultForm").style.display = "block";

                                iterationCount++; // 1 increment after one time, do something different
                            }
                        }
                    }
                }
            }

HTML代码:

                                      

最好的数码单反相机选择......

            

        <div id="selForm">
            <form id="budgetForm">
                <!--show a large print of green font color and size money-->
                Select your DSLR budget range:
                <select id="budgetSel" onChange="onChange();">
                    <!--<option value="selectOneBudget" onMouseOver="changeBackgroundImageSelectOne(this);" selected="selected">Select one</option>
                    <option id="hover500" value="fiveHundredDollars" onMouseOver="changeBackgroundImage500(this);">&lt; $500</option>
                    <option id="hover1000" value="thousandDollars" onMouseOver="changeBackgroundImage1000(this);">&lt; $1000</option>-->
                </select>
            </form>

            <form id="brandForm">
                <!--Show images of the company one by one (fade in, fade out)-->
                Select the DSLR brand you want:
                <select id="brandSel" onChange="onChange();">
                    <!--<option onMouseOver="changeBackgroundImageSelectOne(this);" value="selectOneBrand" selected="selected">Select one</option>
                    <option id="hoverCanon" onMouseOver="changeBackgroundImageCanon(this);" value="Canon">Canon</option>
                    <option id="hoverNikon" onMouseOver="changeBackgroundImageNikon(this);" value="Nikon">Nikon</option>
                    <option id="hoverSony" onMouseOver="changeBackgroundImageSony(this);" value="Sony">Sony</option>
                    <option id="hoverPentax" onMouseOver="changeBackgroundImagePentax(this);" value="Pentax">Pentax</option>-->
                </select>
            </form>

            <form id="typeForm">
                <!--Show stunning beautiful pictures of each type of photography-->
                <!--Select multiples by click CTRL + Left-Click on mouse.-->
                Select the type of photography you plan on doing with a DSLR:
                <select id="typeSel" onChange="onChange();">
                    <!--<option onMouseOver="changeBackgroundImageSelectOne(this);" value="selectOneType" selected="selected">Select one</option>
                    <option id="hoverLandscape" onMouseOver="changeBackgroundImageLandscape(this);" value="Landscape">Landscape</option>
                    <option id="hoverWildlife" onMouseOver="changeBackgroundImageWildlife(this);" value="WildLife">Wildlife</option>
                    <option id="hoverAerial" onMouseOver="changeBackgroundImageAerial(this);" value="Aerial">Aerial</option>
                    <option id="hoverSports" onMouseOver="changeBackgroundImageSports(this);" value="Sports">Sports</option>
                    <option id="hoverPortrait" onMouseOver="changeBackgroundImagePortrait(this);" value="Portrait">Portrait</option>
                    <option id="hoverArchitectural" onMouseOver="changeBackgroundImageArchitectural(this);" value="Architectural">Architectural</option>
                    <option id="hoverMacro" onMouseOver="changeBackgroundImageMacro(this);" value="Macro">Macro</option>-->
                </select>
            </form>

            <form id="lensForm">
                Select the type of lenses you want:
                <select id="lensSel" onChange="onChange();">
                    <!--<option onMouseOver="changeBackgroundImageSelectOne(this);" value="selectOneLens" selected="selected">Select one</option>
                    <option id="hoverPortraitL" onMouseOver="changeBackgroundImagePortraitL(this);" value="portraitLens">Normal &ldquo;Portrait&rdquo; Lens / 35-50mm</option>
                    <option id="hoverTelephoto" onMouseOver="changeBackgroundImageTelephoto(this);" value="telephotoLens">Telephoto Zoom Lens / &gt; 200mm</option>
                    <option id="hoverWide" onMouseOver="changeBackgroundImageWide(this);" value="wideAngleLens">Ultra-Wide Angle Lens / &lt; 35mm</option>-->
                </select>
            </form>
        </div>

        <div id="resultForm">
            <h1>Your DSLR Selections...</h1>
            <form id="result" onsubmit="true">
                <!--Store User Selection Text Node Element Here-->
                <!--<p>Your DSLR budget range selected was:</p>
                <p>The DSLR brand you selected was:</p>
                <p>The type of photography you selected was:</p>
                <p>The type of lenses you selected was:</p>
                <input type="submit" value="Confirm Purchase"/>
                <input type="button" value="Reset All"/>-->
            </form>
        </div>
    </div>
</body>

1 个答案:

答案 0 :(得分:1)

仍然很难说出你在问什么。如果您发布了大量代码,请注意您所询问的代码块中的特定代码行。

我猜测的是当你在这段代码中创建文本节点时:

var pTextBudget, pTextBrand, pTextType, pTextLens;
pTextBudget = document.createTextNode("Your DSLR budget range selected was: " + budText);
//linebreak.appendChild(pTextBudget);
pTextBrand = document.createTextNode("The DSLR brand you selected was: " + brandText);
//linebreak.appendChild(pTextBrand);
pTextType = document.createTextNode("The type of photography you selected was: " + typeText);
//linebreak.appendChild(pTextType);
pTextLens = document.createTextNode("The type of lenses you selected was: " + lensText);                                
//linebreak.appendChild(pTextLens);
// append text to paragraph
pNodeBudget.appendChild(pTextBudget);
pNodeBrand.appendChild(pTextBrand);
pNodeType.appendChild(pTextType);
pNodeLens.appendChild(pTextLens);
// remove pNodes and append changes again

您正在将文本节点分配给局部变量。这些变量仅适用于此功能期间。在下次调用此函数之前,它们不会保留其值。如果你需要它们来保留它们的值,那么你应该将这些变量声明为全局变量(在函数之外),而不是在函数内声明它们。

换句话说,如果您希望变量保留其值,请移动以下行:

 var pTextBudget, pTextBrand, pTextType, pTextLens;

onChange()函数之外,因此变量在一个范围内定义,该范围从一个函数调用到下一个函数。局部变量(在函数内用var声明的变量)仅在函数的一次调用期间存在。函数完成后,这些变量将被销毁,下次调用函数时,会创建新函数。


现在所说的,几乎从来没有一个很好的理由将DOM引用存储到全局变量中的文本节点。您通常在包含ids或类名的<span><div>元素内找到文本节点,并在需要时使用DOM查询查找给定节点。代码往往很多,用这种方式编写得更清晰。我真的不知道代码的重点是什么,而不花费数小时试图理解它,所以我不能推荐一种特定的方法来重写/重构代码以更好地工作。