用于检测选项值的代码未按预期工作

Code to detect option value does not work as expected

本文关键字:工作 代码 检测 选项 用于      更新时间:2023-09-26

我试图在javascript中进行一些字符串比较。我已经看过几个教程和示例,但它们似乎不起作用。我错过了一些基本的东西?

尝试 1

function addAspect(aspect) {
    var print = document.createElement('p');
    var ptext;
    if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}

不行。

然后我找到了这个所有读者都说它工作正常的例子

function addAspect() {
    var print = document.createElement('p');
    var ptext;
    var aspect = String(document.getElementById("aspectResult").value);
    if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}

不行。

我还尝试了.toString()以及'==='完全匹配的比较。

完整代码

<html>
    <head>
    <script type="text/javascript">
        function addAspect()
        {
            var print = document.createElement('p');
            var ptext;
            var aspect = document.getElementById("aspectResult").value;
            if (aspect == "Option1"){
                ptext = document.createTextNode("This is option1");
            }
            print.appendChild(ptext);
            document.getElementById("mainBlock").appendChild(print);
        }
        </script>
    </head>
    <body>
        <form>
            <select id="aspectResult">
                <option value="Option1">Option1</option>
            </select>
            <input type="button" value="Check" onclick="addAspect()"/>
        </form>
        <span id="mainBlock">&nbsp</span>
    </body>
</html>

有什么建议吗?

首先,简要介绍一下下拉菜单的工作原理:

<select id="aspectResult">
    <option value="Option1">Option1</option>
</select>

要从下拉列表中读取所选值,您应该执行以下操作:

var dropdown = document.getElementById('aspectResult'),
selectedValue = dropdown.options[dropdown.selectedIndex].value;

然后,创建包含文本节点的 <p> 元素:

var p = document.createElement('p'),
txt;
if (selectedValue == 'Option1') {
    txt = document.createTextNode('This is option 1');
}

之后,您可以将新创建的段落附加到您选择的容器中:

var container = document.getElementById('mainBlock');
if (txt) {
    p.appendChild(txt);
    container.appendChild(p);
}

现在都在一起!

如果要尝试将

ptext添加到段落中,则需要在末尾添加两行:

function addAspect(aspect) {
    var prnt = document.createElement('p');
    var ptext;
    if( aspect == "Option1" ) {
        ptext = document.createTextNode("This is option1");
        prnt.appendChild(ptext); // Add the text to the paragraph
        document.body.appendChild(prnt); // Add the paragraph to the document
    }
}

您的函数创建了一个文本节点,但随后不对其进行任何操作,因此您的代码似乎什么都不做。 您需要将文本节点附加到 DOM 中某处的元素:

document.body.appendChild(ptext);

您的完整代码似乎在IE9,Firefox 4和Chrome 11中运行良好。 请参阅 http://jsbin.com/ekura5/。