首页 > 解决方案 > 如何从函数 JavaScript 中获取全局变量?

问题描述

当我在下面调用函数名时,我收到了很多错误,例如未定义但该函数运行良好,但是当我尝试从函数或函数名回调全局变量时出现无用的错误。问题是什么?。


    var quoteTex = "";

    function wms() {
      var location = document.getElementsByName("myInput")[0]
      var gwc = location.options[location.selectedIndex].value;
      var layername = location.options[location.selectedIndex].text;
      var url_geoserver = "http://localhost/geoserver/wms
        if (gwc == 2913) {
          var url = L.tileLayer.wms(url_geoserver, {
            layers: 'ap_cadal:bagfinal',
            format: 'image/png',
            version: '1.1.0',
            transparent: true,
            maxZoom: 28
          })
        } else if (gwc == 2912) {
          var url = L.tileLayer.wms(url_geoserver, {
            layers: 'ap_cadas:basw',
            format: 'image/png',
            version: '1.1.0',
            transparent: true,
            maxZoom: 28
          })
        }

        var te = JSON.stringify(url)
        var myjson_p = JSON.parse(te)
        var final = myjson_p["options"]["layers"]
        quoteText = `${final}`

        map.addLayer(url);

      }

      wms();
      console.log(quoteTex)

HTML 

<select  name="myInput" id="choice1" onchange="wmslayers(this);">
        <option value="" disabled selected>Please select </option></li>
     <!-- Pati -->
        <li><option value="2912">Baswari</option></li>
        <li><option value="2913">Bagjiwala</option></li>
</select>

标签: javascripthtmlleaflet

解决方案


考虑将其更改为像下面的示例一样工作。

在函数中返回所需的结果,而不是尝试在函数中设置它,然后将其设置为 = 函数返回值,如下所示。

祝你好运!

var quoteTex = "";

function wms() {
  return text = "test";
}

console.log("1. " + quoteTex);
quoteTex = wms();
console.log("2. " + quoteTex);


推荐阅读