寻找有关多图像交换采取何种方法的建议

时间:2012-12-16 22:45:41

标签: javascript jquery

我正在设计一个互动的大学校园地图,需要一些指导我想做的事。

链接到页面:http://www.torontoclassfind.com/startpage.html

我希望能够点击顶部菜单中的链接(到目前为止只有一个链接处于活动状态并且在左下方div中加载Ajax页面)并让它用不同的图像交换建筑物图像以显示它被选中了。

我可以用以下方法做到这一点:

$("#buildinglink1").click(function () {
   $("#buildingimg1").attr("src","highlightedimage.gif")
})

问题是,一旦点击了另一个菜单链接并选择了新建筑物,我需要将图像更改为默认图像。

建筑图像位于www.torontoclassdfind.com/building/,突出显示的图像位于www.torontoclassdfind.com/buildingc/,两个位置的建筑物名称相同。

我正在考虑使用JQuery的.replace元素来执行此操作(例如:jquery remove part of url),这会删​​除或添加“c”到网址,但我有点迷失在这里。

任何提示?我想我需要创建一个函数来指示链接被选中并以某种方式将它与.replace元素合并。

2 个答案:

答案 0 :(得分:0)

注意:.replace是一个JavaScript字符串(和其他)方法,而不是jQuery方法。

我认为你要求做这样的事情:

$(".any-building").click(function () {
   //replace all building sources with the unhighlighted version
   $(".any-building").attr('src', function () {
      return $(this).attr('src').replace('buildingc', 'building');
   });

   //replace clicked image with highlighted one
   $(this).attr('src', $(this).attr('src').replace('building', 'buildingc'));
});

可能的缺点是,对于大量图像,此交换可能需要很长时间或导致一些闪烁。如果是这种情况,那么您可能希望将类.active添加到突出显示的图像或类似的内容,并仅对该图像和新单击的图像进行交换。

答案 1 :(得分:0)

jQuery中常见的学习错误是关注所有类型选择器的ID。它们适用于非常少量的元素,但对于可以通过更简单的代码方法轻松管理的大量元素,它们变得非常难以处理。

您希望能够编写更多通用代码,其中一个处理程序将覆盖在页面中共享相同功能的所有链接。

示例:

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') );
})

可以看到,通过在一个处理程序中处理元素组可以用很少的代码做很多事情,而不需要关注ID

上面的代码提到可能在数据属性中存储图像URL,例如:

<a href="ajaxUrl?id=345" data-buildingID="345" data-image="imageUrl-345">Building name</a>