[英]How can I get value from dynamically generated select options?
I'm trying to get the value of a selected option that is dynamically generated. 我正在尝试获取动态生成的选定选项的值。 If I hard code the whole thing it works See fiddle . 如果我对整个过程进行硬编码, 请参见小提琴 。 But dynamically nothing works. 但实际上没有任何作用。 When I select the option nothing happens. 当我选择该选项时,什么也不会发生。 What am I doing wrong? 我究竟做错了什么?
markup 标记
<button type="button" id="connect" onclick="login();">
<select id="pages" style="display:none;" onchange="getPage();"></select>
js js
//open login dialog onClick
function login() {
FB.login(function(){
FB.api('/me/accounts/', function(response) {
var pages = document.getElementById('pages');
pages.style.display = 'block';
document.getElementById("connect").style.display="none";
for(var i =0; i < response.data.length; i++)
{
pages[i] = new Option(response.data[i].name,response.data[i].access_token);
}
}
);
}, {scope: 'manage_pages'});
}
function getPage(){
var e = document.getElementById("pages");
var f = e.options[e.selectedIndex].value;
alert(f);
}
You may try to the following: 您可以尝试以下操作:
Replace 更换
pages[i] = new Option(response.data[i].name,response.data[i].access_token);
With 用
pages.options[pages.options.length]=new Option(response.data[i].name,response.data[i].access_token);
After several tests, turns out there is nothing wrong with the initial code. 经过几次测试,结果证明初始代码没有问题。 The problem was that I only had one option which couldn't fire the event. 问题是我只有一个选项无法触发该事件。 To solve that problem I added an empty option to the select. 为了解决该问题,我在选择中添加了一个空选项。
Adding this did the trick: 添加这个就可以了:
document.getElementById("pages").insertBefore(new Option('', ''),
document.getElementById("pages").firstChild);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.