JavaScript:オブジェクトのメソッドを onclick で呼び出す方法
オブジェクトのメソッドを onclick で呼び出す方法を紹介します。
“++”をクリックすると、数値が増加します。
プログラムは以下のようになります。
method_call_by_onclick.htm
<html>
<body>
<div id="index"></div>
<script>
var index1 = new Index(0);
var index2 = new Index(0);
var index3 = new Index(0);
function Index(index) {
this.index = index;
this.span2;
this.increase = function () {
this.span2.innerHTML = ++this.index;
};
var that = this;
var create = function () {
var div = document.createElement("div");
document.querySelector("#index").appendChild(div);
var span1 = document.createElement("span");
span1.onclick = function () {that.increase();};
span1.innerHTML = "++";
div.appendChild(span1);
that.span2 = document.createElement("span");
that.span2.innerHTML = that.index;
div.appendChild(that.span2);
};
create();
}
</script>
</body>
</html>
ここからは、テスト用コードです。無視してください^^
function_call_by_onclick.htm(idの指定なし)
<html>
<body>
<script>
var $index = 0;
var $div = document.createElement("div");
document.body.appendChild($div);
function create() {
var index = "";
index += "<span onclick='increase()'>++</span>";
index += "<span>" + $index + "</span>";
$div.innerHTML = index;
}
function increase() {
$index++;
create();
}
create();
</script>
</body>
</html>
function_call_by_onclick.htm(idの指定あり)
<html>
<body>
<div id="index"></div>
<script>
var $index = 0;
function create(id) {
$id = id;
var index = "";
index += "<span onclick='increase()'>++</span>";
index += "<span>" + $index + "</span>";
document.querySelector(id).innerHTML = index;
}
function increase() {
$index++;
create($id);
}
</script>
<script>
create("index");
</script>
</body>
</html>
test.htm
<html>
<body>
<script>
var index = new Index();
index.show();
function Index() {
this.index;
this.show = function () {
document.write(this.index);
};
var that = this;
var set = function () {
that.index = 0;
};
set();
}
</script>
</body>
</html>
参考サイト
- JavaScriptによるオブジェクト指向プログラミング
- JavaScript でオブジェクトのメンバであるメソッドをイベントハンドラにしたときに非 DOM の this を取りたい
- Javascript: calling object function/method from onclick event, with dynamic argument