简体   繁体   中英

How to get global variable from inside function JavaScript?

When I am calling function name in the below, I am getting lots of errors like undefined but the function is working prefect, but when I am trying to callback global variable from function or function name getting useless errors. What is the problem?.


    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>

Consider changing it to work like the example below.

Return the desired result in the function instead of trying to set it within the function then set it = to the functions return value like below.

Good luck!

 var quoteTex = ""; function wms() { return text = "test"; } console.log("1. " + quoteTex); quoteTex = wms(); console.log("2. " + quoteTex);

Your opening and closing brackets are not matched correctly. You started a block code before your if-else block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM