【发布时间】:2015-02-13 16:20:24
【问题描述】:
我有一个从 JSON 文件填充的选择框,我想重新加载 URL,但从选择框中传递值。
这是我的 index.html 文件的精简版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Timetables</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div id="navbar" class="navbar-collapse collapse">
</div>
<!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<div id="headerArea">
</div>
</div>
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var $crs = GetURLParameter('crs');
// Function that uses this variable removed as not relevant
$.getJSON('csr.json', function (data) {
var stationDropdown = '<form class="navbar-form navbar-right" action="">';
stationDropdown += '<select class="form-control" id="stations">';
for (var i in data) {
stationDropdown += '<option value="' + data[i].Code + '">' + data[i].StationName + '</option>';
}
stationDropdown += '</select>';
stationDropdown += '</form>';
$("#navbar").html(stationDropdown);
});
$(function(){
// bind change event to select
$('#stations').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = 'index.html?crs='.url; // redirect
}
return false;
});
});
</script>
</html>
这里是 JSON 的示例
[
{
"StationName":"Abbey Wood",
"Code":"ABW"
},
{
"StationName":"Aber",
"Code":"ABE"
}
]
选择框生成正常并被“注入(?)到导航栏 div 中,但 on change 事件不会注册
基本上如果有人选择 Aber,onchange 事件会自动重新加载 index.html?crs=ABE。
开发工具没有抛出任何错误,只是当我更改选择框时它什么也没做。
我怀疑我需要将 on change 事件作为一个在需要时专门调用的函数来运行,因为将它放在 index.html 文件的底部意味着它在 DOM 准备好之前加载?
提前感谢您的帮助。
【问题讨论】:
标签: javascript jquery ajax json html