javascript - 通过用户输入通过函数更改全局变量
问题描述
我有一个变量,我希望我的用户能够更改这个变量。变量的原始值应该改变,所以它也可以在另一个函数中使用。(用户输入一个新日期,然后这个变量在 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>
解决方案
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
推荐阅读
- python - 使用文本文件创建统计信息。(Python)
- python-3.x - 如何对包括文本在内的多个列进行分组并使用python在同一数据框上创建新列
- c# - 如何正确地将 XAML 文件移动到文件夹中?
- python - TensorFlow 模型训练——.ipynb 有效,.py 崩溃
- kotlin - Kotlin 自定义计时器每 25hz 滴答一次
- mongodb - 使用所有集合的 mongodump 进行 MongoDB 增量备份
- angular - 如何从投影内容中获取父组件?
- r - 将数据框中的值与其他列中的其他出现匹配
- javascript - 在javascript字符串中连接laravel刀片变量
- aws-glue-spark - 使用 AWS Glue 在 AWS S3 中动态创建文件夹