2017-07-25 24 views
0

這裏,我想分別在按鈕被單擊時在div1上打印「hi」或「hello」。使用javascript在同一個div上調用方法的兩個按鈕

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

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

注:無論是 「喜」 或 「你好」 上DIV1

+2

學會正確使用引號(鳥巢引號),即'的onclick = 「ABC( '你好')」'和'的getElementById(」 div1「)' – Satpal

+1

請不要根據意見/建議更新問題。這會使他們無用。我花了一段時間才明白,你已經根據Satpal的建議更新了問題 – Rajesh

+0

在回答之前請注意注意事項。 –

回答

0

你在你的代碼有一些語法錯誤:

  • 在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>

+0

他們是什麼?請解釋什麼和你爲什麼改變。另請檢查您指出的問題是否已被他人解決 – Rajesh

+0

請注意以下注意事項。 –

+0

你是對的。我現在加了他們。我希望我沒有錯過一次。 – Colin

0

使用下面的代碼片段。 (查看所有報價和拼寫)

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>

+0

你有什麼改變?你爲什麼改變?請解釋。您正在爲讀者作答,而不僅僅是OP – Rajesh

+0

對代碼添加了評論。你還應該閱讀這些文件 –

+0

先生,我知道這個問題是什麼,你有什麼改變。我的觀點是,所有的人都有。專家和初學者。因此,指定什麼和你爲什麼改變將幫助他們理解錯誤 – Rajesh

0

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

相關問題