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

Change URL based on change of dynamic select box

本文关键字:URL 动态 选择      更新时间:2023-10-30

我有一个从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"
  }
]

选择框生成fine并被"注入(?)到导航栏div中,但on change事件不会注册

基本上,如果有人选择Aber,onchange事件将重新加载index.html?crs=自动ABE。

开发工具并没有抛出任何错误,只是在我更改选择框时什么都不做。

我怀疑我需要将on-change事件作为一个在需要时专门调用的函数来运行,因为将其放在index.html文件的底部意味着在DOM准备好之前加载它?

提前感谢您的帮助。

您应该将所有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建议从1.7开始使用on()方法,而不是bind()方法。

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

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

委托事件的优点是,它们可以处理以后添加到文档中的子元素中的事件。

当您动态创建元素时

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

通用语法

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

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

示例

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

总是同一个问题。。。在创建下拉列表之前启动绑定事件,因为它依赖于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
          ........})
});

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

您需要对动态内容使用on

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