Javascript using variables to create a url through

2019-03-03 09:01发布

I have a button on my website that when clicked generates a word. This word is then used in a url call to download a specific file.

 <button class="button1" onclick="myFunction()">cafe</button>
 var cafe = [];
 function myFunction() {
 cafe.push('cafenew');

The 2nd piece of code below takes the word 'cafenew' that was pushed into the var cafe (when the button was clicked) and inserts it into the url address:

 name=cafe

 var src = "https://www.dropbox.com/s/"+name+".kml?dl=1";

But for some reason this does not work. The file being loaded is a layer onto a web map. I have checked the url address, everything is correct. I tested this by using:

 var cafe = "cafenew" 

and the layer loaded correctly, but I obviously loose the function of the button if I fix what the variable equals.

Thanks in advance for any help!

1条回答
在下西门庆
2楼-- · 2019-03-03 09:42

Try this it's working fine :

Html :

<button class="button1" onclick="myFunction();">cafe</button>

Script :

 var cafe = [];
 window.myFunction = function() {
 cafe.push('cafenew');
 console.log(cafe);
 var name = cafe[0];
 var src = "https://www.dropbox.com/s/"+name+".kml?dl=1";
 console.log(src);
 }

Working fiddle : https://jsfiddle.net/8etxu8pr/

查看更多
登录 后发表回答