使用 JQuery 更改标签文本

Apr*_*llo 3 javascript jquery select label

我希望标签在用户从公制更改为英制时更改。

它正确检测更改并存储所选的当前值,进入 if 语句,但随后什么也没有发生。

这是我的 JavaScript。

$(document).ready(function() 
{   
    $("select[name = unit]").change(function()
    {
        var selected = $("option:selected", this).text();

        if(selected == "Metric (cm)")
        {
            $("label[for = unit]").text("mm");
        }
        else if(selected == "Imperial (inches)")
        {
            $("label[for = unit]").text("in");  
        }
    });
})
Run Code Online (Sandbox Code Playgroud)

还有我的html。

    <form name ="Calculator">

        Unit of Measurement: 

        <select name = "unit">

            <option value = "120904000">
                Metric (cm)
            </option>

            <option value = "4760000">
                Imperial (inches)
            </option>

        </select>

        <br>


        Root Diameter: <input type = "text" name = "root" autocomplete = "off">
        <label for = "unit"></label>
        <br>

        Width between bearings: <input type = "text" name = "bearings" autocomplete = "off">
        <label for = "unit"></label>
        <br>

        End Fixity: 
        <select name = "fixity">

            <option value = ".36">
            1
            </option>

            <option value = "1.0">
            2
            </option>

            <option value = "1.47">
            3
            </option>

            <option value = "2.23">
            4
            </option>

        </select>

        <br>

        Max Speed (RPM): <input type = "text" name = "speed" autocomplete = "off"><br>

        <a href = "#" class = "reset" onclick = "">Reset</a>
        <a href = "#" class = "calculate" onclick = "checkOp(); return(false);">Calculate</a>
        <a href = "#" class = "close" onclick = "">Exit</a>

    </form>
Run Code Online (Sandbox Code Playgroud)

sur*_*hel 7

我真的猜不出你在哪里遗漏了。但是请检查我使用你的代码的这个 js fiddle,它对我来说工作得很好。

你的代码小提琴

$("select[name = unit]").change(function()
    {
        var selected = $("option:selected", this).text().trim();

        if(selected == "Metric (cm)")
        {
            $("label[for = unit]").text("mm");
        }
        else if(selected == "Imperial (inches)")
        {
            $("label[for = unit]").text("inches");  
        }   });
Run Code Online (Sandbox Code Playgroud)

我为你更新了 jsfiddle。你需要像这样在最后添加这个修剪:

var selected = $("option:selected", this).text().trim();
Run Code Online (Sandbox Code Playgroud)

然后你就出发了。

这是更新的 jsfiddle :

更新的代码小提琴