ボタンをクリックしたときに JavaScript を実行します:
<button onclick="myFunction()">Click me</button>
Try it Yourself ❯
他の "Try it Yourself" の例が下にあります。
onclick 属性は、要素をマウスでクリックしたときに発火します。
イベント属性 | |||||
---|---|---|---|---|---|
onclick | Yes | Yes | Yes | Yes | Yes |
なし。
<element onclick="script">
値 | 説明 |
---|---|
script | script は onclick で実行される |
サポートする HTML タグ: | 次の要素を除くすべての HTML 要素: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title> |
---|
<p> 要素をクリックすると、テキストの色が赤に変わります:
<p id="demo" onclick="myFunction()">Click me to change my text color.</p>
<script>
function myFunction() {
document.getElementById("demo").style.color = "red";
}
</script>
Try it Yourself ❯
入力フィールドから別の入力フィールドへテキストをコピーするためにボタンをクリックしてください:
<button onclick="myFunction()">Copy Text</button>
<script>
function myFunction() {
document.getElementById("field2").value =
document.getElementById("field1").value;
}
</script>
Try it Yourself ❯
HTML DOM リファレンス:onclick イベント