dimanche 1 novembre 2015

Javascript Vars in onclick

So,pretty much I've run into a problem with my script. I'm trying to make a download script (memory only,so no downloading using HTML/PHP that would cost servers to load more than I want). What I've done is gotten a script off of here (credit Matěj Pokorný). The point is to download a txt file with a random number,it is assigned a var "x", this x is defined in the same script. x is defined as a random number (1-10 * 1000 FLOORED) so example it would be 1234.txt when it downloaded. Unfortunately I have no idea how to define variables in onclick,would someone willing to fix this up for me? I tried moving the variable around and putting the 's around the txt and the whole thing and everything but to no avail. I'm SOO sorry how stupid this is but maybe my crazy stupid question could help someone else.

Script on JSFiddle: http://ift.tt/1NjCW9q

HTML

    <h1>Z</h1>
<p>Z</p>
<button onclick="download(x'.txt', 'Hello world!');" type="button" class="btn btn-lg btn-success btn-block">Download</button>

Javascript

var x = Math.floor((Math.random() * 1000) + 1);function download(filename, text) {
var pom = document.createElement('a');

pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);

if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    pom.dispatchEvent(event);
}
else {
    pom.click();
}




Aucun commentaire:

Enregistrer un commentaire