获取“价值”从使用JavaScript动态生成的下拉列表中取出

Getting the "value" out of a dynamically generated drop down list using JavaScript

本文关键字:下拉列表 动态 JavaScript 价值 获取      更新时间:2023-09-26

当我使用静态下拉列表时,我可以获得值,但一旦我更改为动态生成的列表值总是空白。

有人有什么想法吗?甚至有可能从动态元素中获取值吗?

JS:

$('#input_baseUrl').ready(function(){
    var newSelect=document.createElement('select');
    var selectHTML="";
    for(var count=0; count<services.length; count=count+1){
        var tempString = services[count].split("/");
        var serviceName = tempString[3];
        selectHTML+= "<option value='"+services[count]+"'>"+serviceName+"</option>";
    }
    //iniatilize a new select with the data we provided
    newSelect.innerHTML= selectHTML;
    //find the DOM element that is called input_baseURL
    document.getElementById("input_baseUrl").appendChild(newSelect);
});
function setURL() {
    var url = document.getElementById("input_baseUrl").value;
    alert($('#input_baseUrl').val());  // not sure if jQuery will work here but I have to try
    window.alert("THE URL is: " + url);
    var element = document.getElementById("input_baseUrl");
    var strUser = element.options[element.selectedIndex].value;
    window.alert("Third option is: " +strUser);
}
HTML:

<form id='api_selector'>
     <div class='input' id="input_baseUrl" onchange="setURL()" name="baseUrl" type="text"></div>
     <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
     <div class='input'><a id="explore" href="#">Explore</a></div>
</form>

是的,有可能。但是您必须使用更详细的选择器:

$('#input_baseUrl select option:selected').val();

但是我认为你的HTML在下一行有问题,你的意思是这是两个标签,inputdiv内吗?

<div class='input' id="input_baseUrl" onchange="setURL()" name="baseUrl" type="text"></div>

要修复它,将其分开在两个标签中,并给您的divid:

<form id='api_selector'>
     <div class='input' id="div_baseUrl">
         <input id="input_baseUrl" onchange="setURL()" name="baseUrl" type="text"/>
     </div>
     ...
</form>

你可以从你的ready()函数中添加newSelectdiv:

document.getElementById("div_baseUrl").appendChild(newSelect);
在此之后,您的setUrl()函数可以是:
function setURL() {
    var url = $('#input_baseUrl').val();
    var strUser = $('#div_baseUrl select option:selected').val();
}