jQuery でよくある学習ミスは、すべてのタイプのセレクターの ID に注目することです。それらは非常に少数の要素に対してはうまく機能しますが、単純なコード メソッドで簡単に管理できる要素の大きなグループに対しては非常に扱いにくくなります。
ページ内で同じ機能を共有するすべてのリンクを 1 つのハンドラーでカバーする、はるかに汎用的なコードを記述できるようにしたいと考えています。
例:
var $mainImage=$('#mainImage')
var $buildingLinks=$('.buildingliststyle a').click(function(){
/* "this" is the link clicked*/
/* get index of this link in the whole collection of links*/
var index=$buildingLinks.index(this);
/* perhaps all the image urls are stored in an array*/
var imgUrl= imagesArray( index);
/* perhaps the image urls are stored in data attribute of link( easy to manage when link created server side)*/
var imgUrl=$(this).data('image');
/* store the current image on display (not clear how page is supposed to work)*/
var currImage=$mainImage.attr('src');
$mainImage.data('lastImage', currImage);/* can use this to reset in other parts of code*/
/* nw update main image*/
$mainImage.attr('src', imgUrl);
/* load ajax content for this link*/
$('#ajaxContainer').load( $(this).attr('href') );
/* avoid browser following link*/
return false;
});
/* button to reset main image from data we already stored*/
$('#imageResetButton').click(function(){
$mainImage.attr('src', $mainImage.data('lastImage') );
})
1 つのハンドラーで要素のグループを操作することで、非常に少ないコードで多くのことを実行でき、ID に集中する必要がないことがわかります。
上記のコードは、次のようなデータ属性に画像の URL を保存する可能性について言及しています。
<a href="ajaxUrl?id=345" data-buildingID="345" data-image="imageUrl-345">Building name</a>