首页 > 解决方案 > 通过用户输入通过函数更改全局变量

问题描述

我有一个变量,我希望我的用户能够更改这个变量。变量的原始值应该改变,所以它也可以在另一个函数中使用。(用户输入一个新日期,然后这个变量在 url(调用地图的另一个函数)的末尾被更改,然后显示该日期的数据。)

我知道我必须使我的变量全局化,但我仍然无法工作。这可能是愚蠢的,但我似乎无法让它发挥作用。我究竟做错了什么?

这是一些代码:

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()">

编辑:

我得到了为什么第二个 console.log 在更改后没有显示该值的答案。我想如果我可以让它在我的 html 中工作,那么当我将它粘贴到 JavaScript 中时它会工作,但它仍然不能像我希望的那样工作。下面是所有代码。

当我输入一个新值时,控制台会说:doStuff 没有定义。

所有其他事情都按他们应该的方式工作!

(我与 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>

标签: javascriptfunctionvariablesglobal

解决方案


        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


推荐阅读