Changing global variable by user input via function

不打扰是莪最后的温柔 提交于 2021-01-29 05:06:43

问题


I have a variable and I want my user to be able to change this variable. The original value of the variable should change, so it can be also be used in another function. (The user enters a new date, and this variable then gets changed at the end of the url (of the other function, that calls the map), which then shows the data from that date.)

I know I have to make my variable global, but I still doesn't work. It's probably something dumb, but I just can't seem to make it work. What am I doing wrong?

Here is some of the code:

var date = 1;

function doStuff() {
  var nameElement = document.getElementById("someInput");
  date = nameElement.value;
  console.log(date); //shows after I enter a new value the new value
};

console.log(date); //shows the original value, 1
<input id="someInput" type="text">
<input type="button" value="GoToDate" onClick="doStuff()">

EDIT:

I got the answer to why the second console.log did not display the value once it was changed. I thought that if I could make it work in my html, then it would work in when I pasted it in JavaScript, but it still does not work as I hope it would. Beneath is all the code.

When I enter a new value the console says: doStuff is not defined.

All the other things work as they should!

(I work with NPM)

import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
import TileWMS from 'ol/source/TileWMS.js';

	var inputvp = "2018-10-19 08:00:00";
			
	function doStuff() {
		var nameElement = document.getElementById("someInput");	
		inputvp = nameElement.value;
		console.log(inputvp);
	};
			
   
	  

    var view = new View({
        center: [0, 0],
        zoom: 1
      });

    var map = new Map({
        layers: [wmsLayer],
        target: 'map',
        view: view
      });
<!DOCTYPE html>
<html>
    <head>
		<title>Tiled WMS</title>
		<style>
		  #map {
			width: 500px;
			height: 500px;
		  }
		</style>
	</head> 

  <body>
    <div id="map"></div>
	<input id="someInput" type="text">
	<input type="button" value="GoToDate" onClick="doStuff()">
	<script src="./index.js"></script>
  </body>
</html>

回答1:


First off, I commented out the parts not relevant to the question as I did not have that code.

NOT having a global is a good practice. In order to do that, I created a module that included your function as well as a way to get and set the private value through the module. There are likely simpler ways (not having to do new MyApp) but I used that to show how you can create an instance of the app with unique values. For example you might include var myOtherApp = new MyApp("2017-08-23"); for a second instance.

I also removed the event handler from the markup and added one in the script. The reason your original did not work was because you included your .js file AFTER the markup with a call to it so it was not yet defined. This now works with <script... after that.

I made your map element smaller to show the inputs easier in this example.

I also showed how to set the (now not global) value in the script as well as from the function execution.

I also set the input to the value by default (several ways that could be done)

/*
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
import TileWMS from 'ol/source/TileWMS.js';
*/
var MyApp = function(setDate) {
  /*  Private variables and functions that only
      other private or public functions may access
      and cannot be accessed outside this Module
  */
  // set a date as sent or use the default
  var iAmPrivate = setDate || "2018-10-19 08:00:00";

  /* Properties and methods contained by 
     this object being returned will be public
     and  be accessible in the global scope.
  */
  return {
    set inputvp(value) {
      iAmPrivate = value;
    },
    get inputvp() {
      return iAmPrivate;
    },
    /* probably want parsing of the date etc. in here */
    doStuff: function() {
      var nameElement = document.getElementById("someInput");
      inputvp = nameElement.value;
      console.log(inputvp);
    }
  }
};

// Create a app with data for date text
var myApp = new MyApp("2018-12-13 11:30:00");
console.log(myApp.inputvp);
myApp.inputvp = "2018-7-13 14:22:00"
console.log(myApp.inputvp);
let gotodate = document.getElementById('go-to-date');
let inputDate = document.getElementById('someInput');
// put value in the input (could be done in an app function also)
inputDate.value = myApp.inputvp;
gotodate.onclick = myApp.doStuff;

/*
    var wmsSource = new TileWMS({
      url: 'http://localhost:8080/geoserver/Observations/wms',
      params: {
        'LAYERS': 'Observations:Obs',
        'TILED': true,
        viewparams: 'chosen_timestamp:' + myApp.inputvp
      },
      serverType: 'geoserver',
      crossOrigin: 'anonymous'
    });

    var wmsLayer = new TileLayer({
      source: wmsSource
    });


    var view = new View({
      center: [0, 0],
      zoom: 1
    });

    var map = new Map({
      layers: [wmsLayer],
      target: 'map',
      view: view
    });
    */
#map {
  border: solid lime 1px;
}
<head>
  <title>Tiled WMS</title>
  <style>
    #map {
      width: 50px;
      height: 50px;
    }
  </style>
</head>

<body>

  <div id="map"></div>
  <input id="someInput" type="text" />
  <button type="button" id="go-to-date">GoToDate</button>
  <script src="./index.js"></script>
</body>



回答2:


        var date=1;

        function doStuff() {
            var nameElement = document.getElementById("someInput"); 
            date = nameElement.value;
            console.log(date); //shows after I enter a new value the new value//it is ok because the it show the value after the function was called
        };

      //  console.log(date); //shows the original value, 1// the function hasn't been called yet


来源:https://stackoverflow.com/questions/53760715/changing-global-variable-by-user-input-via-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!