【JS】JavaScriptの実行(外部・内部からの実行)

内部からJavaScriptを実行

構文

<script type="text/javascript">
function 【関数名】()
{
   // 【実行したい内容】
}
</script>

サンプル

<html>
<head>
<title>サンプル</title>
<script type="text/javascript">
function sample()
{
   alert('アラート表示');
}
</script>
</head>
<body>
<button onclick="sample()">ボタン押下でalretが表示</button>
</body>
</html>

外部からJavaScriptを実行

構文

<script src="【外部のJavaScriptファイルのパス】" type="text/javascript">
</script>

サンプル

HTMLファイル:test.html

<html>
<head>
<title>サンプル</title>
<script src="./fromOut.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()">ボタン押下でalretが表示</button>
</body>
</html>

外部のJavaScriptファイル:fromOut.js

function sample()
{
   alert('外部からアラート表示');
}