Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Javascript/jquery从动态下拉列表中访问值_Javascript_Jquery_Html - Fatal编程技术网

如何使用Javascript/jquery从动态下拉列表中访问值

如何使用Javascript/jquery从动态下拉列表中访问值,javascript,jquery,html,Javascript,Jquery,Html,我已经创建了一个动态下拉列表。我想访问从动态创建下拉列表中选择的值。 我的HTML文件 <!DOCTYPE html> 我的js文件: function doc(id){return document.getElementById(id);} function buildCounty(){ var opts=doc('county').options; for(var i=0;i<arr.length

我已经创建了一个动态下拉列表。我想访问从动态创建下拉列表中选择的值。 我的HTML文件

<!DOCTYPE html>

我的js文件:

    function doc(id){return document.getElementById(id);}
        function buildCounty(){
            var opts=doc('county').options;
            for(var i=0;i<arr.length;i++){
                opts[opts.length]=new Option(arr[i][0],arr[i][0]);
            }
            doc('county').onchange=function(){
                this.blur();
                var val=this.value;
                if(!val){return;}
                var co=doc('city').options;
                co.length=1;
                for(var j=0;j<arr.length;j++){
                    if(arr[j][0]!==val){continue;}
                    else{
                        var temp=arr[j][1];
                        for(var k=0;k<temp.length;k++){
                            co[co.length]=new Option(temp[k],temp[k]);
                        }
                        break;
                    }
                }
            }
        }
        function doThis(){

        }
        window.onload=buildCounty;
    </script>

单击按钮,就会调用js文件中存在的函数。在该函数中,我希望访问在第二个城市列表下拉列表中选择的值。

在jQuery中,您可以执行以下操作: 我可以看出你没有任何城市选择的价值。这就是您无法获取值的原因吗?如果是,那么您也需要在标记中填充值。 功能点{ console.log$'city'.val; } 县名: 选择县 城市: 选择城市
看起来您可能可以利用jQuery的更多功能来创建此列表

首先,在Jquery中不需要这一行:

function doc(id) { document.getElementyById(id); }
您可以使用CSS选择器使用jQuery获取元素:

$("#id-of-element");
您甚至可以将其分配给变量:

var countyDropdown = $("#county");
此外,运行jQuery的一种更好的方法是将脚本标记放在文档末尾,然后等待文档引发就绪事件:

$(document).ready(function () { .... });
下面是我编写的一个快速代码笔,它利用jQuery动态填充另一个下拉列表中的选择。它还设置了go按钮,以便在单击时执行某些操作

document.getElementById'city'。值
$(document).ready(function () { .... });