繁体   English   中英

使用javascript在同一个div上调用两个按钮的方法

[英]Two buttons calling method on the same div using javascript

在这里,我想在分别单击按钮时在div1上打印“ hi”或“ hello”。

<buton onclick="abc('hi')"></button>
<button onclick="abc('hello')"></button>
<div id="div1"></div>

<script>
abc(text){
document.getElementById("div1").innerHTML = text;
}
</script>

注意:div1上的“ hi”或“ hello”

使用以下代码段。 (查看所有引号和拼写)

 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> 

您的代码中有一些语法错误:

  • onClick属性中的某些引号有误。 您不能在引号中使用相同的引号(错误: ="func("text")"="func('text')"
  • 您的函数abc未定义为函数
  • getElementById(div1)您必须对div1使用引号。 它正在寻找一个变量。

 function abc(text){ document.getElementById('div1').innerHTML = text; } 
 <button onclick="abc('hi')">hi</button> <button onclick="abc('hello')">hello</button> <div id="div1"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM