JavaScript の onclick を使って実装したコードのサンプルです。
下の「クリック」テキストをクリックすると「クリックOK」に変わります。
クリック
html
<p id="changeText">クリック</p>
JavaScript
const clickChangeText = document.getElementById("changeText");
function clickEvent() {
clickChangeText.textContent = "クリックOK";
};
clickChangeText.onclick = clickEvent;
html
<input type="text" id="cont">
<button type="button" id="btn">入力OK</button>
<div id="output"></div>
JavaScript
const clickBtn = document.getElementById("btn");
const output = document.getElementById("output");
const content = document.getElementById("cont");
function clickEvent02() {
output.innerHTML = "<p>入力内容は「" + content.value + "」です</p>";
}
clickBtn.onclick = clickEvent02;
1
以下の追加ボタンをクリックすると「1」ずつ増えます
html
<p id="num">1</p>
<p>以下の追加ボタンをクリックすると「1」ずつ増えます</p>
<button id="addBtn">1追加</button>
JavaScript
const addBtn = document.getElementById("addBtn");
const num = document.getElementById("num");
function addNum() {
num.textContent = parseInt(num.firstChild.nodeValue) + 1;
}
addBtn.onclick = addNum;
以下のボタンをクリックすると、「1回目のアラート」続けて「2回目のアラート」が表示されます。
以下のボタンをクリックすると、アラートに「ボタン名」と表示されます
html
<button onclick="btnTest01();btnTest02();">クリックでアラートを表示</button>
<input type="button" onclick="outputThis(this)" value="ボタン名">
JavaScript
function btnTest01() {
alert('1回目のアラート');
}
function btnTest02() {
alert('2回目のアラート');
}
function outputThis(name) {
alert(name.value);
}