简体   繁体   中英

Javascript: loops output in div

So i have done some school assignments, and suddenly i just got stuck on this one. This is my script: (its working, but it doesnt show up the way i want to).

function multiplikasjon(){

 var myVar = "i++";
 var minlokke = "";
 for (i=0; i<=100; i++) {
   minlokke += i+ " x " + i+ " = " +(i*i)+ "<br>";
 }
 document.write(minlokke)}

and this is in the body-tag

<a href="javascript:multiplikasjon()">click me</a>

Its working as i want, but i want it to show up when I click a button. I have tried different solutions with a button, but i can't get any output under the button. (Not open a new window, like its doing now).

Thank you for answering!

document.write works only when the page is loaded. To write something when the page is already there, use the following.

HTML:

<div id="div1"> I want the var minlokke here </div>;

JS:

document.getElementById("div1").innerHTML = document.getElementById("div1").innerHTML + minlokke

So what you want to do is execute JavaScript on the click of a button, not just a link?

To do that, use the onclick attribute:

<button onclick="multiplikasjon()">click me</button>

<input type="button" value="click me" onclick="multiplikasjon()" />

You can also assign those properties in JavaScript directly:

myElement.onclick = function() {
    doStuff();
};

In fact, even links should probably be using onclick instead of linking to javascript URLs like you're doing.

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