【问题标题】:Change URL based on change of dynamic select box根据动态选择框的变化改变 URL
【发布时间】: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


    【解决方案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>
    

    另外,作为注释。从 1.7 开始,jQuery 建议使用 on() 方法而不是 bind() 方法。

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

    【讨论】:

    • 不得不对我的更改功能进行细微更改,但这是我成功使用的答案。谢谢
    【解决方案2】:

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

    委托事件的优点是它们可以处理来自后代元素的事件,这些事件会在以后添加到文档中。

    当您动态创建元素时。

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

    一般语法

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

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

    例子

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          动态内容需要使用on

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-31
            • 1970-01-01
            • 2012-09-18
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多