css
body {
color: #252525;
font-family: 'Verdana','MS PGothic','Courier','Lucida Grande','Times New Roman','Consolas','Meiryo','MS Gothic';
font-size: 13pt;
line-height: 150%;
letter-spacing: 1px;
background-color: #888fff;
margin: 20px 50px 20px 50px;
}
AjaxとServletの連携
Ajax と Servlet を連携するやり方について紹介します。サーブレットコンテナは Jetty を用いています。
注)Jetty は、サーブレットコンテナとして機能だけではなく、 Webサーバの機能も備えています。
ファイルの配置
まず、Jetty のzipファイルをダウンロードし、適当な場所(ここでは D:\sdk)で解凍します。 次に webappsフォルダの直下に好きな名前のフォルダ(ここでは webapp)を作成し、更にその下にWEB-INFフォルダを作成し、その中に web.xml を入れて下さい。
D:\sdk\jetty\webapps\webapp\WEB-INF\web.xml
D:\sdk\jetty\webapps\webapp\WEB-INF\classes\SampleServlet.class
注)web.xml、SampleAjax.htm は、UTF-8 で保存してください!
<web-app> <servlet> <servlet-name>sampleservlet</servlet-name> <servlet-class>SampleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>sampleservlet</servlet-name> <url-pattern>sampleservlet</url-pattern> </servlet-mapping> </web-app>
注)SampleServlet1.class、SampleServlet2.class のように、サーブレットが複数ある場合は、<web-app>・・・</web-app>の中に複数記述してください。
1.Ajaxのみのサンプル(Servletなし)
<html>
<body>
<form name="io">
<input type="button" value="実行" onClick="get()">
<textarea id="output" cols="50" rows="5"></textarea>
</form>
<script>
function get() {
xhr = new XMLHttpRequest();
xhr.onload = setResponseText;
xhr.open("GET", "/webapp/hello.txt", true);
xhr.send();
}
</script>
<script>
function setResponseText() {
document.getElementById("output").innerHTML = xhr.responseText;
}
</script>
</body>
</html>
Hello Ajax!
Hello Ajax!
Hello Ajax!
Hello Ajax!
Hello Ajax!
2.AjaxとServletを使ったサンプル(XMLHttpRequest版)
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
<form name="io">
<input type="button" name="execute" value="実行">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="text" name="input3">
<output name="output"></output>
</form>
<script>
document.io.execute.addEventListener("click", function () {
var url = "/webapp/sampleservlet";
var value1 = document.io.input1.value;
var value2 = document.io.input2.value;
var value3 = document.io.input3.value;
var request = "input1" + "=" + value1 + "&" + "input2" + "=" + value2 + "&" + "input3" + "=" + value3;
var callback = function (response) {document.io.output.innerHTML = response["key1"] + "," + response["key2"] + "," + response["key3"];};
$post(url, request, callback);
});
</script>
<script>
function $post(url, request, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
callback(JSON.parse(this.responseText));
}
};
xhr.open("post", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(request);
}
</script>
</body>
</html>
3.AjaxとServletを使ったサンプル(jQuery版)
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<input type="button" id="execute" value="実行">
<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
<output id="output"></output>
</form>
<script>
$("#execute").on("click", function () {
var url = "/webapp/sampleservlet";
var request = {};
request["input1"] = $("#input1").val();
request["input2"] = $("#input2").val();
request["input3"] = $("#input3").val();
var callback = function (response) {$("#output").text(response["key1"] + "," + response["key2"] + "," + response["key3"]);};
$.post(url, request, callback);
});
</script>
</body>
</html>
4.Servletのサンプル(共通)
上記のXMLHttpRequest版及びjQuery版に共通のServletサンプルです。
尚、SampleServlet.java において、サーブレットからクライアントに送信するデータ形式(setContentType)を application/json にしています。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class SampleServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("application/json");
String parameter1 = request.getParameter("input1");
String parameter2 = request.getParameter("input2");
String parameter3 = request.getParameter("input3");
PrintWriter out = response.getWriter();
out.println("{" + "\"key1\"" + ":" + "\"" + parameter1 + "\"" + "," + "\"key2\"" + ":" + "\"" + parameter2 + "\"" + "," + "\"key3\"" + ":" + "\"" + parameter3 + "\"" + "}");
}
}
Servletのコンパイル方法
下記のバッチファイルをダブルクリックして SampleServlet.java をコンパイルします。
set JAVA_HOME=D:\sdk\jdk set path=%JAVA_HOME%\bin javac -cp D:\sdk\jetty\lib\servlet-api-3.1.jar *.java pause
コンパイルしたファイル(SampleServlet.class)を下記のフォルダに入れてください。
Webサーバの起動方法
下記のバッチファイルをダブルクリックすると Jetty が起動します。
set JAVA_HOME=D:\sdk\jdk set path=%JAVA_HOME%\bin cd /d D:\sdk\jetty java -jar start.jar
Webサーバへのアクセス方法
WebブラウザのURLに以下のように入力すれば、Webサーバにアクセスすることができます。
http://localhost:8080/webapp/SampleAjax.htm
参考サイト
- JavaScript初級者から中級者になろう
- 非同期リクエスト
- JavaScript Ajax実装の雛形
- XMLHttpRequestを使う
- Ajaxでサーブレットにアクセスする
- AjaxとServlet:多局面メモ
- URLエンコーディング
- AjaxにおけるJSONの利用
- jQueryのscriptタグsrc指定
- Google:JavaScript addEventListener コールバック関数 引数
- addEventListenerでイベントハンドラに引数を渡す方法
- Passing arguments to callback functions
- 引数をとるコールバック関数の実現の仕方
- リスナー関数に引数を渡す方法
- jQuery.post()
- Javascript:Send JSON Object with Ajax
- xmlHttpRequestでjson形式のデータ送信
- jQueryを利用せずにAjaxを利用するサンプル
- JettyでCGIを使えるように設定
- Google:ユーザ権限でJettyを起動
css
body {
color: #252525;
font-family: 'Verdana','MS PGothic','Courier','Lucida Grande','Times New Roman','Consolas','Meiryo','MS Gothic';
font-size: 13pt;
line-height: 150%;
letter-spacing: 1px;
background-color: #888fff;
margin: 20px 50px 20px 50px;
}
css
body {
color: #252525;
font-family: 'Verdana','MS PGothic','Courier','Lucida Grande','Times New Roman','Consolas','Meiryo','MS Gothic';
font-size: 13pt;
line-height: 150%;
letter-spacing: 1px;
background-color: #888fff;
margin: 20px 50px 20px 50px;
}
夏は花火だ!
最近、花火を見ていないので、久しぶりに見たいな!
JavaScript 備忘録
ドキュメントオブジェクトを操作するモデルをDOM(Document Object Model)と呼びます。
JavaScriptでは、オブジェクトのメンバーをプロパティと呼びます。Javaのフィールドやメソッドに対応します。
Window Object Properties & Window Object Methods
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>hello</title>
<link type="text/css" rel="stylesheet" href="./css/style.css">
</head>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="./js/module.js" charset="utf-8"></script>
<!-- コメント -->
</body>
</html>
表示
F12を押せば、console画面が表示される。
<html>
<body>
<script>
alert("Hello!");
console.log("Hello!");
document.write("Hello!" + "<br>");
document.body.innerHTML += "Hello!" + "<br>";
document.body.insertAdjacentHTML("afterbegin", "aaaaa" + "<br>");
document.body.insertAdjacentHTML("beforeend", "zzzzz" + "<br>");
</script>
</body>
</html>
createElement
classを設定するときは、classNameを使いこと!setAttribute()は使うな!
<html>
<body>
<script>
var button = document.createElement("button");
button.id = "OK";
button.innerHTML = "OK";
button.onclick = function () {$click();};
/*
button.addEventListener("click", function () {
document.querySelector("#output").innerHTML = document.querySelector("#input").value;
});
*/
document.body.appendChild(button);
var input = document.createElement("input");
input.id = "input";
input.type = "text";
input.className = "xxxxx";
document.body.appendChild(input);
var output = document.createElement("output");
output.id = "output";
document.body.appendChild(output);
function $click() {
document.querySelector("#output").innerHTML = document.querySelector("#input").value;
}
</script>
</body>
</html>
createTextNode
<html>
<body>
<script>
var h1 = document.createElement("h1");
var textNode = document.createTextNode("Hello!");
document.body.appendChild(h1);
h1.appendChild(textNode);
</script>
</body>
</html>
要素の選択
children
childNodes
parentNode
firstElementChild
lastElementChild
getElementById("id")
getElementsByName("name")[0](ブラウザごとに動作が異なる場合がある)
getElementsByTagName("tag")[0]
getElementsByClassName("class")[0]
querySelector("#id .class input[type='text']")
querySelectorAll("#id .class input[type='text']")[0]
$(".class").eq(0)
$("#id").find(".class").eq(0)
注)jQueryで使える :checkbox、:radio、:checked などのセレクタをquerySelectorで使うとエラーになります。IE以外のブラウザはサポートしています。
<html>
<body>
<form>
<input type="text" id="text1">
<input type="text" id="text2">
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
document.getElementById("text1").value = "Hello1!";
document.body.insertAdjacentHTML("beforeend", document.getElementById("text1").value);
$("#text2").val("Hello2!");
document.body.insertAdjacentHTML("beforeend", $("#text2").val());
</script>
</body>
</html>
テキストノードの読み・書き
<html>
<body>
<div id="div1"><p>Hello1!</p></div>
<div id="div2"><p>Hello2!</p></div>
<div id="div3"><p>Hello3!</p></div>
<div id="div4"></div>
<div id="div5"></div>
<script>
document.querySelector("#div1").innerHTML += "<p>Goodbye1!</p>";
document.querySelector("#div2").innerText += "<p>Goodbye2!</p>"; //非推奨
document.querySelector("#div3").textContent += "<p>Goodbye3!</p>";
document.querySelector("#div4").innerHTML = document.querySelector("#div1").textContent;
document.querySelector("#div5").textContent = document.querySelector("#div1").innerHTML;
</script>
</body>
</html>
エレメントノードの追加・削除
children → エレメント
childNodes → ノード(エレメント、テキスト)
<html>
<body>
<script>
var div = document.createElement("div");
div.innerHTML = "<p>Hello!</p>";
document.body.appendChild(div);
document.body.removeChild(div);
//document.body.removeChild(document.body.children[1]);
//div.remove();
document.body.innerHTML += document.body.children[0].tagName;
/*
element0.appendChild(element1);
element0.removeChild(element1);
element.parentNode.removeChild(element);
element.removeChild(element.children[0]);
while (element.children[0]) element.removeChild(element.children[0]);
element.remove();(IE:×)
*/
</script>
</body>
</html>
input要素
<html>
<body>
<button onclick="writeOK('#input');">書き込みOK</button>
<button onclick="writeNG('#input');">書き込みNG</button>
<input type="text" id="input" placeholder="入力してください!" readonly>
<input type="search" name="key">
<input type="submit" name="key" value="送信">
<input type="password" value="xxxxxxxxxx">
<input type="time" value="00:00:00">
<script>
function writeOK(id) {
document.querySelector(id).readOnly = false;
}
function writeNG(id) {
document.querySelector(id).readOnly = true;
}
</script>
</body>
</html>
textarea要素
<html>
<body>
<textarea cols="50" rows="10" placeholder="input"></textarea>
</body>
</html>
onclick
<html>
<body>
<input type="button" value="OK" onclick="$echo('#input', '#output');">
<input type="text" id="input">
<output id="output"></output>
<script>
function $echo(input, output) {
document.querySelector(output).innerHTML += document.querySelector(input).value;
}
</script>
</body>
</html>
onchange
<html>
<body>
<input type="checkbox" onchange="$echo('#input', '#output');">
<input type="text" id="input">
<output id="output"></output>
<script>
function $echo(input, output) {
document.querySelector(output).innerHTML += document.querySelector(input).value;
}
</script>
</body>
</html>
value属性の読み書き
<html>
<body>
<input type="text" id="input1">
<input type="hidden" id="input2">
<script>
document.querySelector("#input1").value = "abcde1";
document.querySelector("#input2").value = "abcde2";
document.body.insertAdjacentHTML("beforeend", document.querySelector("#input1").value);
document.body.insertAdjacentHTML("beforeend", document.querySelector("#input2").value);
</script>
</body>
</html>
<html>
<body>
<div id="div">
****************************************************************************************************
</div>
<data id="data">abcde</data>
aaaaaaaaaazzzzzzzzzz
<br><br><br><br><br>
<script>
document.querySelector("#data").value = document.querySelector("#div").textContent;
document.body.innerHTML += document.querySelector("#data").value + "<br>";
document.body.insertAdjacentHTML("beforeend", document.querySelector("#data").value + "<br>");
</script>
</body>
</html>
JSON.parse() と JSON.stringify()
JSON.parse():JSON(文字列) → JavaScriptのオブジェクト
JSON.stringify():JavaScriptのオブジェクト → JSON(文字列)
<html>
<body>
<script>
var object = {};
//var object = new Object();
//object.key0 = "value0";
//object.key1 = "value1";
//object.key2 = "value2";
object["key0"] = "value0";
object["key1"] = "value1";
object["key2"] = "value2";
document.body.innerHTML += JSON.stringify(object) + "<br>";
document.body.innerHTML += JSON.stringify({key0:"value0", key1:"value1", key2:"value2"}) + "<br>";
for (var key in object) {
document.body.innerHTML += key + ":" + object[key] + "<br>";
}
document.body.innerHTML += JSON.stringify({key0:0, key1:"abc", key2:[0, 1, "xyz"]}) + "<br>";
var json = '{"key0":0, "key1":"abc", "key2":[0, 1, "xyz"]}';
var object = JSON.parse(json);
document.body.innerHTML += object["key0"] + "<br>";
document.body.innerHTML += object["key1"] + "<br>";
document.body.innerHTML += object["key2"] + "<br>";
</script>
</body>
</html>
配列
<html>
<body>
<script>
var array = [];
array[0] = "a0";
array[1] = "a1";
array[2] = "a2";
//var array = new Array();
//array.push("a0");
//array.push("a1");
//array.push("a2");
//array.pop();
for (var index in array) {
document.body.innerHTML += index + ":" + array[index] + "<br>";
}
</script>
</body>
</html>
連想配列
連想配列(associative array )を、波括弧(curly bracket){} ではなく、角括弧(square bracket)[] で初期化しても動作した。
<html>
<body>
<script>
var array = [];
//array = {};
array["key1"] = "value1";
array["key2"] = "value2";
array["key3"] = "value3";
for (var key in array) {
document.body.innerHTML += key + ":" + array[key] + "<br>";
}
</script>
</body>
</html>
<html>
<body>
<script>
var dispatch = {};
dispatch["abcde"] = function () {document.write("<p>abcde</p>");};
dispatch["fghij"] = function () {document.write("<p>fghij</p>");};
dispatch["klmno"] = function () {document.write("<p>klmno</p>");};
</script>
<script>
dispatch["abcde"]();
dispatch["fghij"]();
dispatch["klmno"]();
</script>
</body>
</html>
オブジェクト指向プログラミング
以下のプログラムの中で、関数Robotからnewで生成されたrobotはオブジェクトの参照を表わします。
<html>
<body>
<script>
function Robot(x, y) {
this.x = x; // -> public
this.y = y; // -> public
this.move = function (dx, dy) {
this.x += dx;
this.y += dy;
}
this.show = function () {
document.write("x = " + this.x + "<br>");
document.write("y = " + this.y + "<br>");
}
}
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>");
document.write("y = " + robot.y + "<br>");
</script>
<script>
function f(robot) {
robot.x = 2;
robot.y = 2;
}
f(robot);
robot.show();
</script>
</body>
</html>
<html>
<body>
<script>
function Robot(x, y) {
var x = x; // -> private
var y = y; // -> private
this.move = function (dx, dy) {
x += dx;
y += dy;
}
this.show = function () {
document.write("x = " + x + "<br>");
document.write("y = " + y + "<br>");
}
}
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>"); // -> x = undefined
document.write("y = " + robot.y + "<br>"); // -> y = undefined
</script>
</body>
</html>
<html>
<body>
<script>
function Robot(x, y) {
this.x = x; // -> public
this.y = y; // -> public
}
Robot.prototype.move = function (dx, dy) {
this.x += dx;
this.y += dy;
};
Robot.prototype.show = function () {
document.write("x = " + this.x + "<br>");
document.write("y = " + this.y + "<br>");
};
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>");
document.write("y = " + robot.y + "<br>");
robot.print = function () {
document.write("x = " + this.x + "<br>");
document.write("y = " + this.y + "<br>");
};
robot.print();
</script>
</body>
</html>
フォームデータの送信
input要素のname属性とvalue属性の値が下記の形式で送信されます。
http://xxxxx.xxxxx/?name1=value1&name2=value2&name3=value3
<html>
<body>
<form action="http://xxxxx.xxxxx" method="get">
<input name="name1" value="value1">
<input name="name2" value="value2">
<input name="name3" value="value3">
<button>送信</button>
</form>
</body>
</html>
<html>
<body>
<form action="http://www.google.com/search" target="_blank">
<input type="hidden" name="hl" value="ja">
<input type="text" name="hq" placeholder="inurlを入力" size="50">
<input type="text" name="q" placeholder="keywordを入力" size="50">
<input type="submit" value="search">
</form>
</body>
</html>
<html>
<head>
<script>
function request() {
document.requestform.name1.value = document.getElementById("id1").value;
document.requestform.name2.value = document.getElementById("id2").value;
document.requestform.submit();
}
</script>
</head>
<body>
<form>
<input type="text" id="id1" value="value1" size="50" style="font-size:15pt">
<input type="text" id="id2" value="value2" size="50" style="font-size:15pt">
</form>
<form name="requestform" action="http://www.xxxxx.jp/request" target="_blank">
<input type="hidden" name="name1" value="">
<input type="hidden" name="name2" value="">
<input type="button" value="request" onclick="request()" style="width:100px; height:35px; font-size:15pt">
</form>
</body>
</html>
<html>
<body>
<form>
<input type="button" value="実行" onclick="$execute('#input1', '#input2', '#output');">
<input type="text" id="input1">
<input type="text" id="input2">
<output id="output"></output>
</form>
<script>
function $execute(input1, input2, output) {
var url = "/websys/servlet";
var request = {};
request["class"] = "Arithmetic";
request["method"] = "add";
request["input1"] = document.querySelector(input1).value;
request["input2"] = document.querySelector(input2).value;
var callback = function (response) {document.querySelector(output).innerHTML = response["output"];};
$post(url, request, callback);
}
</script>
<script>
function $post(url, request, callback) {
/*
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
callback(JSON.parse(this.responseText));
}
};
*/
var form = document.createElement("form");
var input = document.createElement("input");
form.style.display = "none";
form.method = "post";
form.action = url;
for (var key in request) {
input.name = key;
input.value = request[key].toString();
form.appendChild(input.cloneNode());
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
</script>
</body>
</html>
<html>
<head>
</head>
<body>
<form name="io">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="button" name="button" value="実行" onclick="execute(0)">
<output name="output"></output>
</form>
<script>
function execute(x) {
document.io.output.innerHTML = Number(x) + Number(document.io.input1.value) + Number(document.io.input2.value);
}
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<input type="text" id="input1">
<input type="text" id="input2">
<input type="button" id="button" value="実行">
<output id="output"></output>
</form>
<script>
$("#button").on("click", function () {execute(0);});
//document.getElementById("button").addEventListener("click", function () {execute(0);}, false);
</script>
<script>
function execute(x) {
document.getElementById("output").innerHTML = Number(x) + Number(document.getElementById("input1").value) + Number(document.getElementById("input2").value);
}
</script>
</body>
</html>
<html>
<body>
<input type="text" id="input1">
<input type="text" id="input2">
<output id="output"></output>
<script>
document.getElementById("input1").onkeydown = function (event) {
document.getElementById("output").innerHTML = String.fromCharCode(event.keyCode);
}
</script>
<script>
document.getElementById("input2").onkeyup = function () {
document.getElementById("output").innerHTML = document.getElementById("input2").value;
}
</script>
</body>
</html>
<html>
<body>
<script>
var array = [];
array = ["a0", "a1", "a2", "a3", "a4"];
array = array.concat(["a5", "a6", "a7", "a8", "a9"]);
document.body.innerHTML += array + "<br>";
array.push("a10", "a11", "a12");
document.body.innerHTML += array + "<br>";
array.splice(5, 3, "a15", "a16", "a17");
document.body.innerHTML += array + "<br>";
array.splice(10, 3);
document.body.innerHTML += array + "<br>";
array = array.slice(5, 8);
document.body.innerHTML += array + "<br>";
</script>
<script>
array = ["a0", "a1", "a2", "a3", "a4"];
var string = array.join(",");
document.body.innerHTML += string + "<br>";
array = string.split(",");
document.body.innerHTML += array + "<br>";
string = "abcdefghij";
document.body.innerHTML += string.slice(2) + "<br>";
document.body.innerHTML += string.slice(2, 5) + "<br>";
document.body.innerHTML += string.substr(2, 3) + "<br>";
document.body.innerHTML += string.substring(2, 5) + "<br>";
</script>
</body>
</html>
ある外部ファイル(jsファイル)のグローバル変数を、別の外部ファイルから参照できる。外部ファイルの呼び出し順序に注意。
トップレベルの変数(グローバル変数)には、var が有っても無くても同じ意味。関数内の変数の場合は、var が無いとグローバル変数になる。
<html>
<body>
<script src="./a.js"></script>
<script src="./b.js"></script>
</body>
</html>
var $1 = 1;
var $2 = 2;
var $3 = 3;
document.body.innerHTML += $1 + "<br>";
document.body.innerHTML += $2 + "<br>";
document.body.innerHTML += $3 + "<br>";
<html>
<body>
<script>
var array = ["abcde", "fghij", "klmno"];
document.write(array.indexOf("abcde") + "<br>"); // -> 0
document.write(array.indexOf("fghij") + "<br>"); // -> 1
document.write(array.indexOf("klmno") + "<br>"); // -> 2
</script>
</body>
</html>
<script>
$("#login").on("click", function () {
var url = "/webapp/loginservlet";
var request = {};
request["user"] = $("#user").val();
request["password"] = $("#password").val();
$.post(url, request, redirect);
});
</script>
<script>
function redirect(response) {
if (response["status"] === "success") {
location.href = response["url"];
//location.assign(response["url"]);
//location.replace(response["url"]);
}
else {
$("#message").text(response["error"]);
}
}
</script>
loadイベントの使い方
<html>
<body>
<script>
window.addEventListener("load", function () {
document.getElementById("message").innerHTML += "Hello1!";
});
window.addEventListener("load", function () {
document.getElementById("message").innerHTML += "Hello2!";
});
window.addEventListener("load", function () {
document.getElementById("message").innerHTML += "Hello3!";
});
</script>
<out id="message"></out>
</body>
</html>
テーブル
<html>
<head>
<style>
table {
//width:0;
//table-layout:fixed;
border:2px solid #555eee;
border-collapse:collapse;
}
tr {
height:25px;
}
th input[type="text"] {
font-weight:bold;
text-align:center;
}
tr th:nth-child(1), tr td:nth-child(1) {
width:20px;
text-align:center;
}
tr th:nth-child(2), tr td:nth-child(2) {
//display:none;
}
input[type="text"] {
width:100%;
height:100%;
box-sizing:border-box;
-webkit-box-sizing:border-box;
//font-family:"MS PGothic";
//font-size:15px;
//color:#555555;
}
input {
margin:0;
padding:0;
}
</style>
</head>
<body>
<div id="id_div"></div>
<output id="id_output"></output>
<script>
$makeTable("id_div", 10, 5);
function $makeTable(id_div, rowsLength, columnsLength) {
var table = document.createElement("table");
table.border = 1;
var div = document.getElementById(id_div);
while (div.children[0]) div.removeChild(div.children[0]);
div.appendChild(table);
var thead = document.createElement("thead");
table.appendChild(thead);
var thead_tr = document.createElement("tr");
thead.appendChild(thead_tr);
var th0 = document.createElement("th");
th0.width = 100;
thead_tr.appendChild(th0);
var th_checkbox = document.createElement("input");
th_checkbox.type = "checkbox";
//th_checkbox.onclick = function () {$checkAll(this);};
th0.appendChild(th_checkbox);
var th = [];
for (var j = 0; j < columnsLength; j++) {
th[j] = document.createElement("th");
th[j].innerHTML = "item" + j;
thead_tr.appendChild(th[j]);
}
var tbody = document.createElement("tbody");
table.appendChild(tbody);
var tbody_tr = [];
var td = [];
var input = [];
for (var i = 0; i < rowsLength; i++) {
tbody_tr[i] = document.createElement("tr");
tbody.appendChild(tbody_tr[i]);
var td0 = document.createElement("td");
tbody_tr[i].appendChild(td0);
var td_checkbox = document.createElement("input");
td_checkbox.type = "checkbox";
//td_checkbox.onchange = function () {$makeWritable(this);};
td0.appendChild(td_checkbox);
td[i] = [];
input[i] = [];
for (var j = 0; j < columnsLength; j++) {
td[i][j] = document.createElement("td");
tbody_tr[i].appendChild(td[i][j]);
input[i][j] = document.createElement("input");
input[i][j].type = "text";
input[i][j].readOnly = false;
input[i][j].value = i + "," + j;
td[i][j].appendChild(input[i][j]);
}
}
for (var i = 0; i < tbody.querySelectorAll("tr").length; i++) {
for (var j = 0; j < thead.querySelectorAll("th").length; j++) {
document.getElementById("id_output").innerHTML += tbody.rows[i].cells[j].children[0].value + "<br>";
}
}
}
</script>
</body>
</html>
<html>
<head>
<style>
table {
//width:0;
//table-layout:fixed;
border-collapse:collapse;
//border:2px solid #555eee;
}
tr {
height:25px;
}
th input[type="text"] {
font-weight:bold;
text-align:center;
}
tr th:nth-child(1), tr td:nth-child(1) {
width:20px;
text-align:center;
}
tr th:nth-child(2), tr td:nth-child(2) {
//display:none;
}
input[type="text"] {
width:100%;
height:100%;
box-sizing:border-box;
-webkit-box-sizing:border-box;
//font-family:"MS PGothic";
//font-size:15px;
//color:#555555;
}
input {
margin:0;
padding:0;
}
</style>
</head>
<body>
<div id="id_div"></div>
<script>
$makeTable("id_div", 10, 5);
function $makeTable(id_div, rowsLength, columnsLength) {
var table = "<table border='2' bordercolor='#555eee' bgcolor='#ffffff' cellpadding='1'>";
table += "<thead>";
table += "<tr>";
table += "<th><input type='checkbox'></th>";
for (var j = 0; j < 5; j++) {
table += "<th>item" + j + "</th>";
}
table += "</tr>";
table += "</thead>";
table += "<tbody>";
for (var i = 0; i < rowsLength; i++) {
table += "<tr>";
table += "<td><input type='checkbox'></td>";
for (var j = 0; j < columnsLength; j++) {
table += "<td><input type='text' value=\"" + i + "," + j + "\" readonly></td>";
}
table += "</tr>";
}
table += "</tbody>";
table += "</table>";
document.getElementById(id_div).innerHTML = "";
document.getElementById(id_div).insertAdjacentHTML("afterbegin", table);
};
</script>
</body>
</html>
テーブルにおける行・列の追加・削除
<html>
<head>
<style>
table {
width: 50%;
border-collapse: collapse;
}
</style>
</head>
<body>
<form>
<input type="button" value="追加" onclick="$append();">
<input type="button" value="削除" onclick="$remove();">
</form>
<table id="table0" border="1">
<thead><tr><th><input type="checkbox" class="checkbox" onclick="$checkAll(this);"></th><th>item1</th><th>item2</th><th>item3</th></tr></thead>
<tbody></tbody>
</table>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
document.querySelector("#table0 thead .checkbox").checked = false;
</script>
<script>
function $append() {
var tr = "<tr><td><input type='checkbox' class='checkbox' onchange='$makeEditable(this);'></td><td>data1</td><td>data2</td><td>data3</td></tr>";
//$("#table0 tbody").append(tr);
document.querySelector("#table0 tbody").insertAdjacentHTML("beforeend", tr);
}
</script>
<script>
function $remove() {
//$("#table0 tbody :checked").parent().parent().remove();
var tbody = document.querySelector("#table0 tbody");
/*
var length = tbody.rows.length;
while (length--) {
var checkbox = tbody.rows[length].cells[0].firstElementChild;
if (checkbox.checked === true) {
tbody.deleteRow(length);
}
}
*/
var checkboxes = document.querySelectorAll("#table0 tbody .checkbox");
var length = checkboxes.length;
while (length--) {
if (checkboxes[length].checked === true) {
//tbody.children[length].remove();
tbody.removeChild(tbody.children[length]);
}
}
document.querySelector("#table0 thead .checkbox").checked = false;
}
</script>
<script>
function $checkAll(checkbox) {
var checkboxes = document.querySelectorAll("#table0 tbody .checkbox");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = checkbox.checked;
}
}
</script>
<script>
function $makeEditable(checkbox) {
var tr = checkbox.parentNode.parentNode;
if (checkbox.checked === true) {
tr.contentEditable = true;
}
else {
tr.contentEditable = false;
}
}
</script>
</body>
</html>
ダイアログボックスのフェードイン・フェードアウト
<html>
<head>
<style>
body {
animation: fadein 5s ease 0s 1 normal;
-webkit-animation: fadein 5s ease 0s 1 normal;
}
@keyframes fadein {
0% {opacity: 0;}
100% {opacity: 1;}
}
@-webkit-keyframes fadein {
0% {opacity: 0;}
100% {opacity: 1;}
}
#dialog {
width: 50%;
height: 200px;
background: #555eee;
border-radius: 10px;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<div id="dialog"></div>
</script>
</body>
</html>
<html>
<head>
<style>
#dialog {
width: 50%;
height: 200px;
background: #555eee;
border-radius: 10px;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<input type="button" value="open" onclick="$open();">
<input type="button" value="close" onclick="$close();">
<div id="dialog" class="box" style="visibility:hidden;"></div>
<script>
function $open() {
document.querySelector("#dialog").style.visibility = "visible";
}
function $close() {
document.querySelector("#dialog").style.visibility = "hidden";
}
</script>
</body>
</html>
<html>
<head>
<style>
.box {
opacity: 0;
visibility: hidden;
transition: opacity 2s, visibility 0s ease 1s;
}
.box.visible {
opacity: 1;
visibility: visible;
transition-delay: 0s;
}
#dialog {
width: 50%;
height: 200px;
background: #555eee;
border-radius: 10px;
box-shadow: 10px 10px 10px rgba(0, 0, 0, 1);
}
</style>
</head>
<body>
<input type="button" value="open" onclick="$open();">
<input type="button" value="close" onclick="$close();">
<input type="button" value="toggle" onclick="$toggle();">
<div id="dialog" class="box"></div>
<script>
function $open() {
document.querySelector("#dialog").classList.add("visible");
}
function $close() {
document.querySelector("#dialog").classList.remove("visible");
}
function $toggle() {
document.querySelector("#dialog").classList.toggle("visible");
}
</script>
</body>
</html>
入力チェック
string.match(/regexp/) → stringの中にregexpがあれば最初の文字列を返す。なければnullを返す
string.match(/regexp/g) → stringの中にregexpがあれば全ての文字列の配列を返す。なければnullを返す
[^0-9a-zA-Z] → 英数字以外の一文字を表わす。
if(string.match(/[^0-9a-zA-Z]/)) → stringの中に英数字以外の文字が一文字でもあればtrueになる。
- 【JavaScript入門】try~catchの基本
- JavaScript【try…catch】 ~ 例外処理
- JavaScript で throw new Error() を使ったほうがよい理由
- 【W3Schools】Throw and Try to Catch(Input Validation)
- JavaScript 正規表現で文字列を検索する
- 正規表現で整数や小数を判定する方法
- 文字クラス[]内の否定^
<html>
<body>
<form>
<input type="button" value="OK" onclick="$check('#input', '#output')">
<input type="text" id="input" placeholder="input">
<output id="output"></output>
</form>
<script>
function $check(input, output) {
var input = document.querySelector(input).value;
var output = document.querySelector(output);
try {
if (/[^0-9]/.test(input) || input == "") throw "Input is not a number!"; //0~9以外の文字を含むかどうかをチェック
output.innerHTML = "Input is a number!";
}
catch (e) {
output.innerHTML = e;
}
}
/*
function $check(input, output) {
var input = document.querySelector(input).value;
var output = document.querySelector(output);
try {
if (/^(0|[1-9]\d*)$/.test(input)) throw "Input is a unsigned number!"; //符号無し整数であるかどうかをチェック
output.innerHTML = "Input is not a unsigned number!";
}
catch (e) {
output.innerHTML = e;
}
}
*/
</script>
<script>
document.body.innerHTML += "abc".match(/ab/) + "<br>"; //"ab"を含む文字列
document.body.innerHTML += "abc".match(/[abc]/g) + "<br>"; //"a"、"b"、"c"のいずれかにマッチするかどうかをチェック
document.body.innerHTML += "abc".match(/[^0-9]/g) + "<br>";
document.body.innerHTML += "abc".match(/[^0-9]+/g) + "<br>";
</script>
</body>
</html>
<html>
<body>
<p>正の数を入力してください。平方根が出力されます。</p>
<form>
<input type="button" value="sqrt" onclick="sqrt('#input', '#output')">
<input type="text" id="input" placeholder="input">
<output id="output"></output>
</form>
<script>
function sqrt(input, output) {
var input = document.querySelector(input).value;
var output = document.querySelector(output);
try {
if (input == "") throw "Input is empty!";
if (isNaN(input)) throw "Input is not a number!";
if (Number(input) < 0) throw "Input is a negative number!";
output.innerHTML = Math.sqrt(Number(input));
}
catch (e) {
output.innerHTML = e;
}
}
</script>
</body>
</html>
<html>
<body>
<p>正の数を入力してください。平方根が出力されます。</p>
<form>
<input type="button" value="sqrt" onclick="sqrt('#input', '#output')">
<input type="text" id="input" placeholder="input">
<output id="output"></output>
</form>
<script>
function sqrt(input, output) {
var input = document.querySelector(input).value;
var output = document.querySelector(output);
try {
if (input == "") throw new Error("Input is empty!");
if (isNaN(input)) throw new Error("Input is not a number!");
if (Number(input) < 0) throw new Error("Input is a negative number!");
output.innerHTML = Math.sqrt(Number(input));
}
catch (e) {
output.innerHTML = e.message;
}
}
</script>
</body>
</html>
配置
- 要素を上下左右に中央寄せする色々な方法
- Horizontal and Vertical Centering with CSS
- CSSでheight:100%を使う方法について
- display:tableを活用しよう!
<!doctype html>
<html>
<head>
<style>
html, body {
margin:0;
//padding:0;
height:100%;
}
.center {
display:flex;
height:100%;
align-items:center;
justify-content:center;
-webkit-align-items:center;
-webkit-justify-content:center;
}
</style>
</head>
<body>
<table class="center" border="1" bordercolor="blue" style="border-collapse:collapse;">
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
</table>
</body>
</html>
<!doctype html>
<html>
<head>
<style>
html, body {
margin:0;
//padding:0;
height:100%;
}
.table {
display:table;
width:100%;
height:100%;
}
.vertical_center {
display:table-cell;
vertical-align:middle;
}
.horizontal_center {
display:table;
margin:auto;
}
</style>
</head>
<body>
<div class="table">
<div class="vertical_center">
<div class="horizontal_center">
<table border="1" bordercolor="blue" style="border-collapse:collapse;">
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
<!doctype html>
<html>
<head>
<style>
html, body {
margin:0;
//padding:0;
height:100%;
}
.table {
display:table;
width:100%;
height:100%;
}
.vertical_center {
display:table-cell;
vertical-align:middle;
}
.horizontal_center {
display:table;
margin:auto;
}
.box {
display:table-cell;
text-align:center;
vertical-align:middle;
width:300px;
height:200px;
background-color:blue;
}
</style>
</head>
<body>
<div class="table">
<div class="vertical_center">
<div class="horizontal_center">
<div class="box">
xxxxxxxxxx<br>
xxxxxxxxxx<br>
xxxxxxxxxx<br>
</div>
</div>
</div>
</div>
</body>
</html>
<!doctype html>
<html>
<head>
<style>
.center {
display:table;
margin:auto;
}
.center {
//margin-left:auto;
//margin-right:auto;
}
.center {
//left:0;
//right:0;
//margin:auto;
}
</style>
</head>
<body>
<table class="center" border="1" bordercolor="blue" style="border-collapse:collapse;">
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
<tr>
<td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td><td>xxxxx</td>
</tr>
</table>
</body>
</html>
<html>
<head>
<style>
html, body {
//width:100%;
//height:100%;
}
.outter {
//position:relative;
height:100%;
//width:200px;
//height:200px;
background:silver;
}
.inner {
width:100px;
height:100px;
background:blue;
}
.center {
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
}
</style>
</head>
<body>
<div class="outter">
<div class="inner center">
Hello!
</div>
</div>
</body>
</html>
<html>
<head>
<style>
html, body {
//width:100%;
//height:100%;
}
.outter {
//position:relative;
height:100%;
//width:200px;
//height:200px;
background:silver;
}
.inner {
width:100px;
height:100px;
background:blue;
}
.center {
position:relative;
top:100px;
margin:auto;
}
</style>
</head>
<body>
<div class="outter">
<div class="inner center">
Hello!
</div>
</div>
</body>
</html>
<html>
<head>
<style>
.outter {
position:relative;
width:200px;
height:200px;
background:silver;
}
.inner {
width:100px;
height:100px;
background:blue;
}
.center {
position:absolute;
top:50px;
right:0;
left:0;
margin:auto;
}
</style>
</head>
<body>
<div class="outter">
<p>xxxxxxxxxx</p>
<div class="inner center">
Hello!
</div>
</div>
</body>
</html>
<html>
<head>
<style>
.outter {
width:200px;
height:200px;
background:silver;
}
.inner {
width:100px;
height:100px;
background:blue;
}
.center {
position:relative;
top:50px;
right:0;
left:0;
margin:auto;
}
</style>
</head>
<body>
<div class="outter">
<p>xxxxxxxxxx</p>
<div class="inner center">
Hello!
</div>
</div>
</body>
</html>
<html>
<body>
<div style="position:relative;">
<div style="float:left;">
aaaaa
</div>
<div style="float:right;">
bbbbb
</div>
<div style="clear:both;">
ccccc
</div>
<div style="position:absolute; bottom:0; right:0;">
ddddd
</div>
</div>
</body>
</html>
表示・非表示
<html>
<body>
<input type="radio" id="radio0" name="menu" checked="false" onclick="$switch()">menu0<br>
<input type="radio" id="radio1" name="menu" checked="false" onclick="$switch()">menu1<br>
<input type="radio" id="radio2" name="menu" checked="false" onclick="$switch()">menu2<br>
<div id="box0" style="display:none; width:500px; height:300px; background:#777777;">box0</div>
<div id="box1" style="display:none; width:500px; height:300px; background:#555eee;">box1</div>
<div id="box2" style="display:none; width:500px; height:300px; background:#eee555;">box2</div>
<script>
document.querySelector("#radio0").checked = true;
document.querySelector("#box0").style.display = "block";
function $switch() {
var radios = document.getElementsByName("menu");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
for (var j = 0; j < radios.length; j++) {
document.querySelector("#box" + j).style.display = "none";
}
document.querySelector("#box" + i).style.display = "block";
break;
}
}
}
</script>
</body>
</html>
<html>
<body>
<input type="button" value="表示" onclick="document.querySelector('#box').style.display='block';">
<input type="button" value="非表示" onclick="document.querySelector('#box').style.display='none';">
<div id="box" style="display:none">
<p>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
</p>
</div>
<div>
<p>
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
</p>
</div>
</body>
</html>
<html>
<body>
<input type="button" value="表示" onclick="document.querySelector('#box').style.visibility='visible';">
<input type="button" value="非表示" onclick="document.querySelector('#box').style.visibility='hidden';">
<div id="box" style="visibility:hidden">
<p>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
</p>
</div>
<div>
<p>
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy<br>
</p>
</div>
</body>
</html>
iframe
- iframeの動的実装
- iframeの中身を差し替える
- iframeの中身を動的に書き換える
- iframe を動的生成する際の注意点
- IFrame contentWindow Property
- IFrame contentDocument Property
- Chromeでローカルファイルをiframeで表示したときの注意
- JavaScriptを動的に実行する
- iframe.contentDocument.location.replace()
- window.frames[0].location
- frames
<!doctype html>
<html>
<body>
<iframe id="id_iframe" src="sub1.html" width="300" height="200" frameborder="1"></iframe>
<input id="id_input" type="text" value="">
<input type="button" value="Print" onclick="$print();">
<script>
function $replaceSrc(src) {
document.getElementById("id_iframe").contentWindow.location.replace(src);
}
</script>
<script>
function $print() {
document.body.innerHTML += document.getElementById("id_iframe").contentWindow.document.getElementById("id_input").value;
}
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<h1>sub1.html</h1>
<input id="id_input" type="text" value="">
<input type="button" value="OK" onclick="$hoge();">
<script>
function $hoge() {
//window.parent.document.getElementById("id_input").value = "Hello!";
//window.parent.$replaceSrc('sub2.html');
window.top.document.getElementById("id_input").value = "Hello!";
window.top.$replaceSrc('sub2.html');
}
</script>
</body>
</html>
<!doctype html>
<html>
<body>
<h1>sub2.html</h1>
<input id="id_input" type="text" value="">
</body>
</html>
2次元配列
<html>
<body>
<script>
var array2d = [];
for (var i = 0; i < 10; i++) {
array2d[i] = [];
for (var j = 0; j < 20; j++) {
array2d[i][j] = "(" + i + "," + j + ")";
}
document.body.innerHTML += array2d[i].join(',') + "<br>";
}
</script>
</body>
</html>
var & let
<html>
<body>
<script>
function printx() {
let x = 0;
document.body.innerHTML += x + "<br>";
{
let x = 1;
document.body.innerHTML += x + "<br>";
}
document.body.innerHTML += x + "<br>";
}
printx();
</script>
<script>
function printy() {
var y = 0;
document.body.innerHTML += y + "<br>";
{
var y = 1;
document.body.innerHTML += y + "<br>";
}
document.body.innerHTML += y + "<br>";
}
printy();
</script>
</body>
</html>
セレクタ
.aaa.bbb {} と .aaa .bbb {} は、意味が異なるので注意!
.aaa.bbb {} は、<div class="aaa bbb"></div>のような要素に対する設定!
#aaa.bbb {} は、<div id="aaa" class="bbb"></div>のような要素対する設定!
.aaa .bbb {} → aaa の子孫である bbb (直下でなくてもよい)
.aaa > .bbb {} → aaa の直下にある bbb
尚、.abc は、*.abc を表す。
- CSS Selector Reference
- CSSセレクタの種類
- CSSの#と.の違い
- CSSで複数のセレクタ名を並べる時の注意点
- 【jQuery】要素を指定するセレクタの使い方のまとめ
- jQueryの代わりにquerySelectorを使うと良いかもよ♪
- jQueryのfindなどをquerySelectorで書く
<html>
<head>
<link rel="stylesheet" type="text/css" href="sample.css">
</head>
<body>
<div id="id1">aaaaa</div>
<div class="class1">bbbbb<div class="class2">ccccc</div>ddddd</div>
</body>
</html>
div#id1 {color: red;}
div.class1 {color: blue;}
div.class1 > div.class2 {color: green;}
<html>
<body>
<div>
<p>aaaaa</p>
<p>bbbbb</p>
<p>ccccc</p>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("p").eq(0).css("color", "blue");
$("div").find("p").eq(2).css("color", "red");
Array.from(document.querySelectorAll("p"), element => document.body.innerHTML += element.textContent);
</script>
</body>
</html>
$(".abc").eq(0); -> jQuery Object
document.querySelectorAll(".abc")[0]; -> NodeList
$(element).find(".abc").eq(0); -> jQuery Object
element.querySelectorAll(".abc")[0]; -> NodeList
<form>
<input type="button" id="ibutton" value="実行">
<input type="button" class="cbutton" value="実行">
</form>
<script>
$("#ibutton").on("click", function () {.....});
$(".cbutton").on("click", function () {.....});
</script>
Default Parameter
注)ECMAScript 5.1 で undefined は書き換え不可になった。
<html>
<body>
<script>
function f(x) {
if (x === undefined) {
x = "Hello!";
}
document.body.innerHTML += x + "<br>";
}
/* IE NG
function f(x = "Hello!") {
document.body.innerHTML += x + "<br>";
}
*/
</script>
<script>
f();
f(null);
f(undefined);
f("Goodbye!");
</script>
</body>
</html>
(function () {
.....
} ());
<br>: line break
参考サイト
- Google:JavaScript addEventListener コールバック関数 引数
- addEventListenerでイベントハンドラに引数を渡す方法
- 引数をとるコールバック関数の実現の仕方
- リスナー関数に引数を渡す方法
- Google:JavaScript hoisting
- 即時関数(immediate function)とは?
- Google:idセレクタ classセレクタ
- Google:onkeydown
- JavaScriptの配列の使い方まとめ。(連結、追加、挿入、削除、取得)
- 文字列切り出し(slice, substr, substring)
- JavaScriptによるリダイレクトと問題点
- Window Object
- Windowオブジェクト
- windowオブジェクトとグローバルの実態について
- JavaScript:グローバル変数とローカル変数
- [JavaScript]変数宣言におけるvar省略時の注意点
- document を window.document と書かない理由
- document.getElementByIdを使わないで要素を取得
- ラベル付きbreak文とcontinue文
- Google:JavaScript 3重 クォーテーション
- HTMLではwidthやheightに単位(px)はつけない方が良いの?
- 他のウェブページにリダイレクトする方法
- jQueryでページ遷移をする方法とサンプル
- JavaScriptでリダイレクト(自動ページ遷移)するには?
- location.hrefとlocation.replace()の違い
- jQuery.get(url, request, callback)
- application/x-www-form-urlencoded
- Convert JavaScript object to x-www-form-urlencoded format
- encodeURIComponent()(RFC 3986仕様を忠実に順守するには)
- encodeURIComponentが世界基準だと誤解してた話
- JavaScriptのエスケープ(encodeURIComponent)
- URL Encoding (Percent Encoding)
- JSON(RFC 4627)
- JSON
- javax.json.Json めんどくさすぎる
- JSONの記述方法(サーバからJSONで出力する場合には、バックスラッシュをエスケープする必要がある)
- JSONでエスケープが必要な文字
- JSONのエスケープ
- JSONにマルチバイト文字が含まれる場合は注意(JSON.stringifyを使う際の注意)!
- JavaScriptのシングルクォーテーションとダブルクォーテーション
- Convert JavaScript object to x-www-form-urlencoded format
- Google:setRequestHeader(X-Requested-With,XMLHttpRequest)
- XMLHttpRequestによるXSSへの対処(jQueryやprototype.jsなどのライブラリでは、自動的に上記のリクエストヘッダーを付与してくれます)
- リクエストとレスポンスの仕組み(Content-Type:multipart/form-data)
- Referer(the address of the previous webpage)
- 20 jQuery Plugins For Page Transition Effects With CSS3
- new Array()と[]の違い(コンストラクタとリテラルの違い)
- What is the difference between `new Object()` and object literal notation?
- 最近のAjaxの書き方
- Google:async await
- JavaScriptでバイナリデータの送信・受信
- How to create multipart/form-data?(バイナリデータの送信)
- JavaScriptでバイナリデータの送信と受信(blobを使う)
ビールが飲みたい!
ビールがおいしい季節ですね!