私は本からいくつかのサンプルコードを調べています。コードには、次のようなサムネイルのセットがあります。
<div id="thumbnailPane">
<img src="images/itemGuitar.jpg" alt="guitar" width="301" height="105"
title="itemGuitar" id="itemGuitar" />
<img src="images/itemShades.jpg" alt="sunglasses" width="301" height="88"
title="itemShades" id="itemShades" />
<img src="images/itemCowbell.jpg" alt="cowbell" width="301" height="126"
title="itemCowbell" id="itemCowbell" />
<img src="images/itemHat.jpg" alt="hat" width="300" height="152"
title="itemHat" id="itemHat" />
</div>
サムネイルをクリックすると、次の機能で大きな画像が表示されます。
function initPage() {
// find the thumbnails on the page
thumbs = document.getElementById("thumbnailPane").getElementsByTagName("img");
// set the handler for each image
for (var i = 1; i < thumbs.length; i++) {//CHANGED FROM 0 TO 1
image = thumbs[i];
// create the onclick function
image.onclick = function() {
// find the image name
detailURL = 'images/' + this.title + '-detail.jpg';
document.getElementById("itemDetail").src = detailURL;
getDetails(this.title);
}
}
}
私はそれがどのように機能するかを理解しています。私が疑問に思っているのは、ハードコードされた単一の関数でそれを複製できるかどうかです。onclick
基本的に私が欲しいのは、イベントハンドラー( )で呼び出されるすべてのサムネイルに共通の単一の関数でクリックされたときにサムネイルのタイトルを取得することですonclick="getImage()"
。
クリックしたばかりの要素のtitle
またはを取得するにはどうすればよいですか?id
私はjQueryを使用していないので、JSの回答が必要です。
編集:
getImage()
私はこのような関数を書こうとしました:
function getImage(){
var title = this.title;
detailURL='images/' + title + '-detail.jpg';
document.getElementById("itemDetail").src = detailURL;
}
これは機能しません。の値はvar title
です"undefined"
。