全局变量不会被函数,范围事实修改

时间:2022-08-12 00:42:24

I am trying to update a variable value after a selection in a HTML select. In the jQuery function the value is ok, but after that, the value still is the same that before the function:

我试图在HTML选择中选择后更新变量值。在jQuery函数中,值是正确的,但在此之后,该值仍然与函数之前的值相同:

Code:

toRet = null;
//var selector = document.getElementById("id_event_type")
//var valorSeleccionado = selector.options[selector.selectedIndex].value;
$(document).ready(function(){           
  slc = $('#id_event_type');

  slc.on('change', function(){

    toRet = parseInt(slc.find(":selected").val(), 10);//here is ok!, $(this) same result

   });
    //from here toRet is null                       
   if (toRet == 2){
     var eventIcon = new OpenLayers.Icon('/static/img/accidente.png', eventSize, eventOffset);
   }
  if (toRet == 0){
    var eventIcon = new OpenLayers.Icon('/static/img/obrasMarker.png',   eventSize, eventOffset);
  }
  if (toRet == 1){
    var eventIcon = new OpenLayers.Icon('/static/img/atascoMarker.png', eventSize, eventOffset);
  }

  eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition,   eventIcon));
  eventMarkerslayer.setVisibility(false);
  $( "#visibilityEvents" ).change(function() {
      if ($('#visibilityEvents').is(":checked")) {
          eventMarkerslayer.setVisibility(true);
      } else {
          eventMarkerslayer.setVisibility(false);
      }
  });
});

Here I put the entire HTML:

在这里我把整个HTML:

Hole HTML:

{% extends "base.html" %}
        {% block styles %}
        <link rel="stylesheet" type="text/css" media="screen" href="/static/css/bootstrap-datetimepicker.css">
        <link rel="stylesheet" type="text/css" media="screen" href="/static/css/style.css">
        <style type="text/css">
            body {
                padding-top: 10px;
                padding-bottom: 40px;
            }
            /* Custom container */
            .container-narrow {
                margin: 0 auto;
                max-width: 1000px;
            }
            .container-narrow > hr {
                margin: 30px 0;
            }
            .marketing {
                margin: 10px 0;
            }
            .marketing p + h4 {
                margin-top: 28px;
            }
            .errorlist {
                 color:red;
            }
            #map {
                width: 100%;
                height: 500px;
            }
            @media only screen and (max-width: 1000px) {
                /* Force table to not be like tables anymore */
                #no-more-tables table,
                #no-more-tables thead,
                #no-more-tables tbody,
                #no-more-tables th,
                #no-more-tables td,
                #no-more-tables tr {
                    display: block;
                }

                /* Hide table headers (but not display: none;, for accessibility) */
                #no-more-tables thead tr {
                    position: absolute;
                    top: -9999px;
                    left: -9999px;
                }

                #no-more-tables tr { border: 1px solid #ccc; }

                #no-more-tables td {
                    /* Behave  like a "row" */
                    border: none;
                    border-bottom: 1px solid #eee;
                    position: relative;
                    padding-left: 50%;
                    white-space: normal;
                    text-align:left;
                }

                #no-more-tables td:before {
                    /* Now like a table header */
                    position: absolute;
                    /* Top/left values mimic padding */
                    top: 6px;
                    left: 6px;
                    width: 45%;
                    padding-right: 10px;
                    white-space: nowrap;
                    text-align:left;
                    font-weight: bold;
                }

                /*
                Label the data
                */
                #no-more-tables td:before { content: attr(data-title); }
          }
        </style>
        {% endblock %}
        {% block body %}
        <div  class="container-narrow">
            <div class="masthead">
                <ul class="nav nav-pills pull-right" style="margin-top: 50px;">
                    <li><a href="/logout/">Cerrar sesi&oacute;n</a></li>

                </ul>
                <h3 class="muted">
                    <img src="/static/img/compass4D-logo.png" width="300px" height="143px"/>
                </h3>
            </div>

            <hr>
            {% load widget_tweaks %}
            <div class="row-fluid marketing">
                <div class="span6">
                    <form action="" method="post" >{% csrf_token %}
                        <fieldset>
                            <legend>Añadir Evento </legend>
                            <div class="control-group">
                                <label class="control-label">Tipo de evento:</label>
                                <div class="controls">
                                    {{ form.event_type }}
                                    {{ form.event_type.errors }}
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">Posici&oacute;n del evento:</label>
                                <div class="controls form-inline">
                                    {% render_field form.lat_position placeholder="Latitude" %}
                                    {% render_field form.lon_position placeholder="Longitude" %}
                                    {{ form.lat_position.errors }}
                                    {{ form.lon_position.errors }}
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">Sentido:</label>
                                <div class="controls">
                                    {{ form.direction }}
                                    {{ form.direction.errors }}
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label">Tiempo de expiraci&oacute;n:</label>
                                <div class="controls">
                                    <div id="datetimepicker" class="input-append date">
                                       {% render_field form.expiry_time data-format="MM/dd/yyyy hh:mm:ss" placeholder="MM/dd/yyyy hh:mm:ss" %}
                                        <span class="add-on">
                                            <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
                                        </span>
                                    </div>
                                    {{ form.expiry_time.errors }}
                                </div>
                            </div>
                            <button class="btn btn-large btn-primary" name="add_road_event" type="submit">Añadir evento</button>
                        </fieldset>
                    </form>
                </div>

                <div class="span6">
                    <div class="controls form-inline">
                        <label class="checkbox">
                            <input id="addMarkerSelected" type="checkbox" checked="checked"> Seleccionar posici&oacute;n
                        </label>
                        <label class="checkbox" style="float:right; margin-top:6px;">
                            <input id="visibilityEvents" type="checkbox"> Visualizar todos los eventos
                        </label>
                    </div>
                    <div id="map"></div>
                </div>
            </div>

            <div class="row-fluid marketing" style="margin-top:25px;">
                <form action="" method="post">{% csrf_token %}
                    <fieldset>
                        <legend>Lista de eventos activos</legend>
                        {% if road_events|length %}
                        <section id="no-more-tables">
                            <table class="table-bordered table-striped table-condensed cf">
                                <thead class="cf">
                                   <tr>
                                      <th>#</th>
                                      <th>Fecha creación</th>
                                      <th>Evento</th>
                                      <th>Latitud</th>
                                      <th>Longitud</th>
                                      <th>Sentido</th>
                                      <th>Tiempo expiración</th>
                                   </tr>
                               </thead>
                               <tbody>
                         {% for event in road_events %}
                                 <tr>
                                     <td data-title="#">
                                        <label class="checkbox">
                                        <input id="{{event.id}}" name="{{event.id}}" type="checkbox" >
                                        </label>
                                     </td>
                                     <td data-title="Fecha creación">{{ event.created }}</td>
                                     <td data-title="Evento">{{ event.get_event_type_display }}</td>
                                     <td data-title="Change">{{ event.lat_position }}</td>
                                     <td data-title="Latitud">{{ event.lon_position }}</td>
                                     <td data-title="Sentido">{{ event.get_direction_display }}</td>
                                     <td data-title="Tiempo expiración">{{ event.expiry_time }}</td>
                                 </tr>
                                   {% endfor %}
                              </tbody>
                          </table>
                        </section>
                            <button class="btn btn-large btn-danger" style="margin-top:25px;" name="remove_road_event" type="submit">Eliminar eventos</button>
                        {% else %}
                        Actualmente no hay ningun evento activo.
                        {% endif %}
                    </fieldset>
                </form>
            </div>

            <div class="span10" >
            <table width="100%" border="1" bgcolor="#EFFBF8" style="border-collapse:collapse; table-layout:fixed;">
                <tr>
                    <td colspan="3" rowspan="2" align="center"><b>Zona corredor</b>
                    <th colspan="3" align="center" >Prioridad a bus</th>
                </tr>
                <tr>
                    <td align="center"><b>Solicitada</b></td>
                    <td align="center"><b>Prioridad<br> habilitada
                    </b></td>
                    <td align="center"><b>Activada</b></td>
                </tr>
                <tr>
                    <td colspan="3" bgcolor="#FAAC58">Zona 1 (Avda. Madrid ascendente)</td>
                    <td align="center">
                        <div id="zv1"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="1" type="checkbox" />
                                    {% for i in zone %}
                            {% if i.id == 1 %}
                                    {% if i.****_pet == True %}
                             <img width="40px" src="/static/img/check.png"> <br />
                             <input type="submit" value="Deshabilitar"/>
                                    {%else%} <br/>
                            <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                            <div id="zs1"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" bgcolor="#66CC66">Zona 2 (Avda. Madrid
                        descendente)</td>
                    <td align="center">
                    <div id="zv2"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="2" type="checkbox" />
                                 {% for i in zone %}
                                    {% if i.id == 2 %}
                                    {% if i.****_pet == True %}
                                        <img width="40px" src="/static/img/check.png"> <br />
                                        <input type="submit" value="Deshabilitar"/>
                                    {%else%} <br/>
                                        <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                    {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                            <div id="zs2"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" bgcolor="#FFFF00">Zona 3 (Gran V&iacute;­a  descendente)</td>
                    <td align="center">
                        <div id="zv3"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="3" type="checkbox" />
                                    {% for i in zone %}
                                        {% if i.id == 3 %}
                                            {% if i.****_pet == True %}
                                        <img width="40px" src="/static/img/check.png"> <br />
                                        <input type="submit" value="Deshabilitar"/>
                                            {%else%} <br/>
                                        <input type="submit" value="Habilitar" />
                                            {%endif%}
                                        {%endif%}
                                    {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                        <div id="zs3"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" bgcolor="#58ACFA">Zona 4 (Gran V&iacute;a ascendente)</td>
                    <td align="center">
                        <div id="zv4"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                        <input hidden checked name="zone_id" value="4" type="checkbox" />
                                {% for i in zone %}
                                {% if i.id == 4 %}
                                {% if i.****_pet == True %}
                        <img width="40px" src="/static/img/check.png"> <br />
                        <input type="submit" value="Deshabilitar"/>
                                {%else%} <br/>
                        <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                    {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                        <div id="zs4"></div>
                    </td>
                </tr>
        <tr>
                    <td colspan="3" bgcolor="#FAAC58" style="word-wrap:break-word;">Zona 5 (B.Aires-Autopista hasta Rot. Jenaro de la Fuente-Túnel Martínez Garrido)</td>
                    <td align="center">
                        <div id="zv5"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="5" type="checkbox" />
                                    {% for i in zone %}
                            {% if i.id == 1 %}
                                    {% if i.****_pet == True %}
                             <img width="40px" src="/static/img/check.png"> <br />
                             <input type="submit" value="Deshabilitar"/>
                                    {%else%} <br/>
                            <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                            <div id="zs5"></div>
                    </td>
                </tr>
        <tr>
                    <td colspan="3" bgcolor="#FAAC58">Zona 6 (Rot. Jenaro de la Fuente-Túnel Martínez Garrido hasta B.Aires-Autopista)</td>
                    <td align="center">
                        <div id="zv6"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="6" type="checkbox" />
                                    {% for i in zone %}
                            {% if i.id == 1 %}
                                    {% if i.****_pet == True %}
                             <img width="40px" src="/static/img/check.png"> <br />
                             <input type="submit" value="Deshabilitar"/>
                                    {%else%} <br/>
                            <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                            <div id="zs1"></div>
                    </td>
                </tr>
        <tr>
                    <td colspan="3" bgcolor="#FAAC58">Zona 7 (Julián Estévez hasta Rot.Jenaro de la Fuente-Túnel Martínez Garrido)</td>
                    <td align="center">
                        <div id="zv7"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="7" type="checkbox" />
                                    {% for i in zone %}
                            {% if i.id == 1 %}
                                    {% if i.****_pet == True %}
                             <img width="40px" src="/static/img/check.png"> <br />
                             <input type="submit" value="Deshabilitar"/>
                                    {%else%} <br/>
                            <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                            <div id="zs7"></div>
                    </td>
                </tr>
        <tr>
                    <td colspan="3" bgcolor="#FAAC58">Zona 8 ( Rot.Jenaro de la Fuente-Túnel Martínez Garrido hasta Julián Estévez)</td>
                    <td align="center">
                        <div id="zv8"></div>
                    </td>
                    <td align="center">
                        <form action="/pet_****/" method="GET">
                                {% csrf_token %}
                             <input hidden checked name="zone_id" value="8" type="checkbox" />
                                    {% for i in zone %}
                            {% if i.id == 1 %}
                                    {% if i.****_pet == True %}
                             <img width="40px" src="/static/img/check.png"> <br />
                             <input type="submit" value="Deshabilitar"/>
                                    {%else%} <br/>
                            <input type="submit" value="Habilitar" />
                                    {%endif%}
                                    {%endif%}
                                {% endfor %}
                        </form>
                    </td>
                    <td align="center">
                            <div id="zs8"></div>
                    </td>
                </tr>
                <tr>

            </table>
        </div>


            <legend><br><br> </legend>

      <div class="footer" style="text-align:right;">

        <a href="http://www.ctag.com"><img src="/static/img/CTAG-logo.png" width="200px" height="100px"/></a>
        <a href="http://www.grupoetra.com"><img src="/static/img/****-logo.png" width="116px" height="100px"/></a>
        <a href="http://www.vitrasa.es"><img src="/static/img/vitrasa-logo.png" width="134px" height="100px"/></a>
        <a href="http://hoxe.vigo.org"><img src="/static/img/vigo-logo.png" width="100px" height="100px"/></a>
      </div>
        </div> <!-- /container -->

        <!-- Javascript -->
        <!-- Placed at the end of the document so the pages load faster -->

    <script type="text/javascript">


    function sync_vitrasa(id){
        $.ajax({
         url: "/vitrasa_state/",
         type:"GET",
         data: {
           id: id,
         },success: function( data ) {
            id="#zv"+id;

             $(id).html(data);

         }
       });

    }

    function sync_pet(id){
        $.ajax({
         url: "/traffic_ligths_state/",
         type:"GET",
         data: {
           id: id,
         },success: function( data ) {
            id="#zs"+id;

             $(id).html(data);

         }
       });

    }
    /*setInterval("sync_vitrasa(1)",2000);
    setInterval("sync_vitrasa(2)",2000);
    setInterval("sync_vitrasa(3)",2000);
    setInterval("sync_vitrasa(4)",2000);

    setInterval("sync_pet(1)",2000);
    setInterval("sync_pet(2)",2000);
    setInterval("sync_pet(3)",2000);
    setInterval("sync_pet(4)",2000);*/




    </script>

        <script src="/static/js/jquery.js"></script>
        <script src="/static/js/bootstrap.min.js"></script>
        <script src="/static/js/bootstrap-datetimepicker.min.js"></script>
        <script src="/static/js/openLayers/OpenLayers.js"></script>
        <script type="text/javascript">
            $(function() {
                $('#datetimepicker').datetimepicker({
                    language: 'pt-BR'
                });
            });

            var options = {
            controls: [
                new OpenLayers.Control.Navigation(),
                new OpenLayers.Control.PanZoomBar(),
                new OpenLayers.Control.Attribution()
            ]
            };

            var map = new OpenLayers.Map("map", options);
            map.addLayer(new OpenLayers.Layer.OSM());
            var center = new OpenLayers.LonLat(-8.7181,42.2265);
            center.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
            map.setCenter(center,14);

            var markers = new OpenLayers.Layer.Markers( "Markers" );
            markers.id = "Markers";
            map.addLayer(markers);

            map.events.register("click", map, function(e) {
                if ($('#addMarkerSelected').is(":checked")) {
                    var position = map.getLonLatFromPixel(e.xy);
                    var positionESPG = map.getLonLatFromPixel (e.xy).transform (map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"));
                    $('#id_lat_position').val(positionESPG.lat);
                    $('#id_lon_position').val(positionESPG.lon);
                    var size = new OpenLayers.Size(32,32);
                    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
                    var icon = new OpenLayers.Icon('/static/img/newMarker.png', size, offset);
                    var markerslayer = map.getLayer('Markers');
                    while(markerslayer.markers.length > 0){
                        markerslayer.removeMarker(markerslayer.markers[0]);
                    }
                    markerslayer.addMarker(new OpenLayers.Marker(position,icon));
                }
            });

            eventPositions = {{road_events_json|safe}};

            if (eventPositions.length > 0) {
                var eventMarkers = new OpenLayers.Layer.Markers( "Events" );
                eventMarkers.id = "Events";
                map.addLayer(eventMarkers);
                var eventMarkerslayer = map.getLayer('Events');
                for (var i= 0; i < eventPositions.length; i++) {
                    var eventPosition = new OpenLayers.LonLat(eventPositions[i][1],eventPositions[i][0]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
                    var eventSize = new OpenLayers.Size(24,24);
                    var eventOffset = new OpenLayers.Pixel(-(eventSize.w/2), -eventSize.h);
                    var toRet = null;
                    //var selector = document.getElementById("id_event_type")
                    //var valorSeleccionado = selector.options[selector.selectedIndex].value;
                    $(document).ready(function(){           
                        slc = $('#id_event_type');

                        slc.on('change', function(){


                            toRet = parseInt($(this).val(), 10);
                            alert(toRet);
                            //window['toRet'] = parseInt(slc.find(":selected").val(), 10);
                        });
                        alert(toRet);
                        if (toRet == 2){

                            var eventIcon = new OpenLayers.Icon('/static/img/accidente.png', eventSize, eventOffset);
                        }
                        if (toRet == 0){

                            var eventIcon = new OpenLayers.Icon('/static/img/obrasMarker.png', eventSize, eventOffset);
                        }

                        if (toRet == 1){

                            var eventIcon = new OpenLayers.Icon('/static/img/atascoMarker.png', eventSize, eventOffset);
                        }

                        //var eventIcon = new OpenLayers.Icon('/static/img/accidente.png', eventSize, eventOffset);
                        eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition, eventIcon));

                        eventMarkerslayer.setVisibility(false);
                        $( "#visibilityEvents" ).change(function() {
                            if ($('#visibilityEvents').is(":checked")) {
                                eventMarkerslayer.setVisibility(true);
                            } else {
                                eventMarkerslayer.setVisibility(false);
                            }
                        });
                    });
            }
            }
            $(".olControlAttribution").css("bottom","-1.5em");

        </script>
        {% endblock %}

1 个解决方案

#1


0  

This is happening because you are modifying your global variable toRet only in case of some particular change/ event whereas you're checking the condition inside document.ready but outside the change function. Try putting the condition inside change function and the value should definitely reflect.

发生这种情况是因为您正在修改全局变量toRet仅在某些特定更改/事件的情况下,而您正在检查document.ready中的条件但在更改函数之外。尝试将条件置于更改函数内,值应该明确反映。

    slc.on('change', function(){

        toRet = parseInt(slc.find(":selected").val(), 10);//here is ok!, $(this) same result
        //from here toRet is null  
    if (toRet == 2){
         var eventIcon = new OpenLayers.Icon('/static/img/accidente.png', eventSize, eventOffset);
       }
      if (toRet == 0){
        var eventIcon = new OpenLayers.Icon('/static/img/obrasMarker.png',   eventSize, eventOffset);
      }
      if (toRet == 1){
        var eventIcon = new OpenLayers.Icon('/static/img/atascoMarker.png', eventSize, eventOffset);
      }

eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition,   eventIcon));
  eventMarkerslayer.setVisibility(false);
  $( "#visibilityEvents" ).change(function() {
      if ($('#visibilityEvents').is(":checked")) {
          eventMarkerslayer.setVisibility(true);
      } else {
          eventMarkerslayer.setVisibility(false);
      }
  });
       });

#1


0  

This is happening because you are modifying your global variable toRet only in case of some particular change/ event whereas you're checking the condition inside document.ready but outside the change function. Try putting the condition inside change function and the value should definitely reflect.

发生这种情况是因为您正在修改全局变量toRet仅在某些特定更改/事件的情况下,而您正在检查document.ready中的条件但在更改函数之外。尝试将条件置于更改函数内,值应该明确反映。

    slc.on('change', function(){

        toRet = parseInt(slc.find(":selected").val(), 10);//here is ok!, $(this) same result
        //from here toRet is null  
    if (toRet == 2){
         var eventIcon = new OpenLayers.Icon('/static/img/accidente.png', eventSize, eventOffset);
       }
      if (toRet == 0){
        var eventIcon = new OpenLayers.Icon('/static/img/obrasMarker.png',   eventSize, eventOffset);
      }
      if (toRet == 1){
        var eventIcon = new OpenLayers.Icon('/static/img/atascoMarker.png', eventSize, eventOffset);
      }

eventMarkerslayer.addMarker(new OpenLayers.Marker(eventPosition,   eventIcon));
  eventMarkerslayer.setVisibility(false);
  $( "#visibilityEvents" ).change(function() {
      if ($('#visibilityEvents').is(":checked")) {
          eventMarkerslayer.setVisibility(true);
      } else {
          eventMarkerslayer.setVisibility(false);
      }
  });
       });