根据动态选择框的更改更改URL

时间:2015-02-13 16:20:24

标签: javascript jquery ajax json html5

我有一个从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准备好之前加载它?

提前感谢您的任何帮助。

5 个答案:

答案 0 :(得分:1)

事件处理程序仅绑定到当前选定的元素;它们必须存在于您的代码进行事件绑定调用时的页面上。

  

委托事件的优势在于它们可以处理来自稍后添加到文档的后代元素的事件。

正在动态创建元素。

您需要使用Event Delegation。您必须使用委托事件方法来使用.on()

一般语法

$(document).on(event, selector, eventHandler);

理想情况下,您应该将document替换为最近的静态容器。

实施例

$("#navbar").on('change', '#stations', function(){
   //Your code
});

答案 1 :(得分:1)

始终是同一个问题...在创建下拉列表之前启动绑定事件,因为它取决于ajax调用。

您的代码出了什么问题:

$.getJSON('csr.json', function (data) {  // This is done #1
        .......
        $("#navbar").html(stationDropdown); // this is done #3 : creating #stations.
    });

$('#stations').bind('change', function () { // This is done #2 and won't do anything because #stations doesn't exist yet
  ........
        });

正确的方法是:

$.getJSON('csr.json', function (data) {  // This is done #1
              .......
        $("#navbar").html(stationDropdown); // this is done #2 : creating #stations.
        $('#stations').bind('change', function () { // This is done #3
          ........})
});

答案 2 :(得分:1)

这是因为在$(function(){之后调用$ .getJSON函数 如果你将代码移到$(function(){中,到$ .getJSON函数的末尾,那么它就可以工作。

答案 3 :(得分:1)

您应该将所有HTML内容移到HTML中。

getJSON()内,您可以将代码缩减至:

var stations = $( '#stations' );
for (var i in data) {
    stations.append( '<option value="' + data[i].Code + '">' + data[i].StationName + '</option>' );
}

一旦你这样做,其他一切都应该适当。这是我在HTML中更改的内容:

<div id="navbar" class="navbar-collapse collapse">
    <form class="navbar-form navbar-right" action="">
        <select class="form-control" id="stations">
            <option>Select One</option>
        </select>
    </form>
</div>

另外,作为一个说明。 jQuery建议使用on()方法,而不是1.7版本的bind()方法。

http://api.jquery.com/bind/

答案 4 :(得分:0)

您需要将on用于动态内容:

$('#navbar').on('change', '#stations', function () {
    ^ Static container content is appended to
                              ^ #stations = target element
相关问题