简体   繁体   中英

JavaScript onClick attribute into variable

var user = [];
function doFunction()
{
    for(l=0;l<3;l++)
    {
        user.push(prompt("Bitte Mindestens 6 Zahlen von 1-49 eingeben" + "Abfrage Nr. " + (l + 1)));
    }
}
doFunction();
document.write("Ihre Eingaben: " + user);

This is the working code, but I dont want that the function gets activated after refreshing the site, so I added this button: and deleted doFunction(); in the script so it looked kinda like this:

<input type="button" value="Viel Glueck!" onClick="doFunction();">
<script>
    var user = [];
    function doFunction()
    {
        for(l=0;l<3;l++)
        {
            user.push(prompt("Bitte Mindestens 6 Zahlen von 1-49 eingeben" + "Abfrage Nr. " + (l + 1)));
        }
    }
    document.write("Ihre Eingaben: " + user);
</script>

the script gets executed after pressing the button, but the variable is not working anymore(it doesnt save the output) can anyone please help me with my problem?

Try to move the document.write inside the function like this:

var user = [];
    function doFunction()
    {
        for(l=0;l<3;l++)
        {
            user.push(prompt("Bitte Mindestens 6 Zahlen von 1-49 eingeben" + "Abfrage Nr. " + (l + 1)));
        }
          document.write("Ihre Eingaben: " + user);
    }

As already pointed out, you might want to move the document.write into your function. However, I would like to point out that using document.write to begin with is a bad idea in almost all situations.

Why? It only works while the page is "open", ie is being loaded. When the user press the button the page will most likely have finished loading. The browser will then reopen it, and in doing so erasing all content. Read more about it here , or check this fiddle out.

Instead, if you want to write something to the page using JavaScript, use the DOM. First create a div that will contain the content:

<div id="message" />

Then when you want to write something, in your case in the doFunction , fill the div with content like this:

document.getElementById("message").innerHTML = "Ihre Eingaben: " + user;

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