Here, I want to print either"hi" or "hello" on div1 when button are clicked respectively.
<buton onclick="abc('hi')"></button>
<button onclick="abc('hello')"></button>
<div id="div1"></div>
<script>
abc(text){
document.getElementById("div1").innerHTML = text;
}
</script>
Note:Either "hi" or "hello" on div1
Use below code snippet. (See all quotes and spellings)
function abc(text){ // Added 'function' keyword so javascript can recognize a function has started document.getElementById("div1").innerHTML = text; // add " " before and after div1. getElementById() takes a string argument and strings are wrapped within " " }
<button onclick="abc('hi')"></button> <!-- onclick() takes string argument wrapped within " " .. function abc() also takes string argument. strings are wrapped within " " or '' (double and single Quotes) --> <button onclick="abc('hello')"></button> <!-- Same as above --> <div id="div1"></div>
You had a few syntax errors in your code:
="func("text")"
right ="func('text')"
) abc
was not defined as a function getElementById(div1)
you have to use quotes for div1
. It was looking for a variable. function abc(text){ document.getElementById('div1').innerHTML = text; }
<button onclick="abc('hi')">hi</button> <button onclick="abc('hello')">hello</button> <div id="div1"></div>
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.