从 javascript 中的下拉函数读取变量

read variable from dropdown function in javascript

我在 html 文件中使用这个下拉菜单:

<select id="read-type"  onchange="checkrt()">                           
                    <option value="1">2word</option>                    
                    <option value="2">3word</option>
                    <option value="3">line</option>
                    </select>
            </div>

并阅读:

var dro = document.getElementById("read-type");
var readtype = dro.options[dro.selectedIndex].value;

但是这段代码无法读取 "onchange" 或者我不知道怎么办?所以我将代码更改为:

$(function checkrt(){
    $('#read-type').on('change', function(){        
        window.readtype = $(this).val();
        alert(readtype);
    });
})

最后的代码与 "alert" 配合使用效果很好,但我无法通过以下函数读取下一个函数中的变量 "readtype":

    Function delta(text){
if (readtype == 1) 

这给我味精(未定义读取类型)?请问是什么问题。

注意:如果我在下拉列表中更改所选项目后单击浏览器中的 "refresh" 按钮,代码可以获得 readtype。

您不需要命名函数来包含 onchange 触发器。要访问该值,您必须将 readtype 传递到下一个函数中。

将您的代码更改为:

$(function(){
    $('#read-type').on('change', function(){        
        var readtype = $(this).val();
        nextFunction(readtype);
    });

    function nextFunction(readtype){
        if (readtype == 1) {
            alert(readtype);
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="read-type">
    <option value="1">2word</option>
    <option value="2">3word</option>
    <option value="3">line</option>
</select>