与脚本在DOM之前运行相关的全局变量的问题

时间:2019-07-13 00:07:57

标签: javascript jquery html dom

我将所有代码都放在下面。我基本上有一个JSON文件,在其中填充下拉列表并创建表。我有一个脚本,可让我根据下拉列表过滤表格。

我希望能够使用下拉列表的值的索引来确定表中显示的信息。

我添加了注释来解释不同的部分。

我将如何处理?

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script type="text/javascript"></script>

  <!-- this is a dropdown -->
  <select id="locality-dropdown" name="locality" onchange="javascript:filterByCategory(this)">
    <option value="AB">Alberta</option>
  </select>

  <!-- this lets me filter a table below using the dropdown-->
  <script>
    function filterByCategory(obj) {
      var id = $(obj).val(); // get currently selected value

      $('tr[position]').hide(); // first hide all rows
      $('tr[position=' + id + ']').show(); // show only those rows with the requested category id
    }
  </script>

  <!-- this is to populate my dropdown -->
  <script>
    let dropdown = $('#locality-dropdown');

    dropdown.empty();

    dropdown.append('<option selected="true" disabled>Choose State/Province</option>');
    dropdown.prop('selectedIndex', 0);

    var url = 'climate.json';

    // Populate dropdown with list of provinces
    $.getJSON(url, function(json) {
      for (var i = 0; i < json.length; i++) {
        dropdown.append($('<option></option>').text(json[i].city));
      };
    });
  </script>

  <!-- THIS IS THE SCRIPT WHERE I GET THE INDEX -->
  <script>
    var indexofdropdown;
    $(document).ready(function() {
      $("#locality-dropdown").change(function() {
        window.indexofdropdown = $("#locality-dropdown").prop('selectedIndex');
      });
      console.log($("#locality-dropdown").prop('selectedIndex'));
    });
  </script>

  <!-- script to populate table -->
  <script>
    function onLoad() {

      var url = 'climate.json';
      $.getJSON(url, function(json) {
        var table = $('<table id="myTable">');
        table.attr('border', '1');

        var tr = $('<tr>');
        var td = $('<td>');
        td.html(Object.keys(json[0])[0]);
        tr.append(td);
        td = $('<td>');
        td.html('City');
        tr.append(td);
        td = $('<td>');
        td.html('Country');
        tr.append(td);

        for (var j = 0; j < 5; j++) {

          // here is where i start using the global variable
          var tr = $('<tr position=' + json[$("#locality-dropdown").prop('selectedIndex')].city + '>');
          var td = $('<td>');
          td.html(Object.keys(Object.values(json[$("#locality-dropdown").prop('selectedIndex')])[3][0])[j]);
          tr.append(td);
          td = $('<td>');
          td.html(json[indexofdropdown].city);
          tr.append(td);
          td = $('<td>');
          td.html(json[indexofdropdown].country);
          tr.append(td);

          table.append(tr);
        }

        //}
        $('body').append(table);
      });
    }
  </script>
</head>

<body onload="onLoad();"></body>

</html>

0 个答案:

没有答案