如何将输入给定值获取到数组

我正在根据一些 Json 数据开发计算器输入的值未定义


这就是我的代码的样子


   

<!DOCTYPE html>

<html>

<head>


</head>

<body>



<form action="" id="my-form">

  <div class="form-group">

    <label for="">Enter Lat</label>

    <input type="text" id="lat" step="any">

    <label for="">Enter Long</label>

    <input type="textr" id="long" step="any">


  </div>

  <input type="button" id="Btn" value="Calculate" >

  <h2 id="result">result</h2>

</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>

var desiredLat = document.getElementById("lat").value,

desiredLong = document.getElementById("long").value;

  const

  myData = {

   "datagrid": [

     { "GRIDCODE": 1735,"lat": 35.91511132, "long": -5.401484264 },

     { "GRIDCODE": 1805, "lat": 35.90677815, "long": -5.468149593 },

     { "GRIDCODE": 1808, "lat": 35.90677815, "long":-5.459816427 },

     { "GRIDCODE": 1784, "lat": 35.89844499, "long":-5.476482759 }

   ]

 };


潇湘沐
浏览 62回答 1
1回答

呼如林

zero你得到值的原因是因为你lookupGridcodeByLatAndLong在第一次调用你的函数时传递了你的lat和lang值,这两个值都将返回 undefined 因为你还没有输入它们。你必须用值填充它们,然后在你进行计算之前点击按钮来获取lat和值,实际上你不需要将你的对象值解析为参数,因为你将它初始化为全局参数,所以你仍然可以在你的函数中使用它而不解析它。langGRIDCODE<!DOCTYPE html><html><head></head><body><form action="" id="my-form">&nbsp; <div class="form-group">&nbsp; &nbsp; <label for="">Enter Lat</label>&nbsp; &nbsp; <input type="text" id="lat" step="any">&nbsp; &nbsp; <label for="">Enter Long</label>&nbsp; &nbsp; <input type="textr" id="long" step="any">&nbsp; </div>&nbsp; <input type="button" id="Btn" value="Calculate" >&nbsp; <h2 id="result">result</h2></form><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><script>&nbsp; const&nbsp; myData = {&nbsp; &nbsp;datagrid: [&nbsp; &nbsp; &nbsp;{ "GRIDCODE": 1735,"lat": 35.91511132, "long": -5.401484264 },&nbsp; &nbsp; &nbsp;{ "GRIDCODE": 1805, "lat": 35.90677815, "long": -5.468149593 },&nbsp; &nbsp; &nbsp;{ "GRIDCODE": 1808, "lat": 35.90677815, "long":-5.459816427 },&nbsp; &nbsp; &nbsp;{ "GRIDCODE": 1784, "lat": 35.89844499, "long":-5.476482759 }&nbsp; &nbsp;]&nbsp;};function lookupGridcodeByLatAndLong(lat, long){&nbsp; let gridcode = 0;&nbsp;&nbsp;&nbsp; var result = myData.datagrid.find(x => x.lat == lat && x.long == long)&nbsp; if (result) {&nbsp; &nbsp; gridcode = result.GRIDCODE;&nbsp; }&nbsp;&nbsp; return gridcode;}$("#Btn" ).click(function() {&nbsp; var lat = document.getElementById("lat").value,&nbsp; long = document.getElementById("long").value;&nbsp; var result = lookupGridcodeByLatAndLong(lat, long)&nbsp; $("#result").html(result);});</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript