戻る

JavaScriptでテキストを変更する

JavaScriptでテキストを変更する

イベントハンドラ(body要素に記述)

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function changeText(){
	document.getElementById("first").innerText = "変更後";
	
	//HTML5の場合、document.getElementById("ID名")は下のように省略できます。
	//first.innerText = "変更後";
}
</script>
</head>
<body>
	<p id="first">変更前</p>
	<p>
	<input type="button" value="変更" onclick="changeText();">
	</p>
</body>
</html>

イベントハンドラ(scriptタグ内に記述)

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
window.onload = function(){
	document.getElementsByTagName("input")[0].onclick = function(){
		document.getElementById("first").innerText = "変更後";
		
		//HTML5の場合、document.getElementById("ID名")は下のように省略できます。
		//first.innerText = "変更後";
	}
}
</script>
</head>
<body>
	<p id="first">変更前</p>
	<p>
	<input type="button" value="変更">
	</p>
</body>
</html>

イベントリスナ

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
window.addEventListener("load",function(){
	document.getElementsByTagName("input")[0].addEventListener("click",function(){
		document.getElementById("first").innerText = "変更後";
		 
		//HTML5の場合、document.getElementById("ID名")は下のように省略できます。
		//first.innerText = "変更後";
	});
});
</script>
</head>
<body>
	<p id="first">変更前</p>
	<p>
	<input type="button" value="変更">
	</p>
</body>
</html>

jQueryのclick関数

<!DOCTYPE html>
<html lang="ja-JP">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=yes,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.5">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
	$("input").click(function(){
		$("#first").text("変更後");
	});
});
</script>
</head>
<body>
	<p id="first">変更前</p>
	<p>
	<input type="button" value="変更" />
	</p>
</body>
</html>

inserted by FC2 system