2010-10-17 128 views
1

我有一个UL李菜单等类使用jQuery加载图片?

<ul> 
    <li><a href="#1">Image #1</a></li> 
    <li><a href="#2">Image #2</a></li> 
    <li><a href="#3">Image #3</a></li> 
    <li><a href="#4">Image #4</a></li> 
</ul> 

而且我有喜欢的图像的容器:

<div id="image-container"> 
    <img src="images/1.jpg"> 
</div> 

我想改用在“图像容器”的图像采用div “散”和“负荷”(每一个图像是/图像/文件夹,每一个被命名为像哈希值,所以负载图像/ 2.JPG等

我想是这样的:

$("#ul li:nth-child(1)").click(function(e) { 
     e.preventDefault(); 
     var hash = this.parentNode.hash; 
     $("#image-container").load('images/'+ hash.substring(1) +'.jpg'); 

$("#ul li:nth-child(2)").click(function(e) { 
     e.preventDefault(); 
     var hash = this.parentNode.hash; 
     $("#image-container").load('images/'+ hash.substring(1) +'.jpg'); 

$("#ul li:nth-child(3)").click(function(e) { 
     e.preventDefault(); 
     var hash = this.parentNode.hash; 
     $("#image-container").load('images/'+ hash.substring(1) +'.jpg'); 

(...) 

但它不能很好地工作(我想我需要的东西与负载稍有不同,因为它不会改变我的图像?)。

非常感谢。

顺便说一句 - 有没有办法写我的jQuery代码更短(在一个函数中,因为现在我有多个相同的主体)?

非常感谢, 阿达:)

回答

2

你可以写你的代码有点短这样的:

$("ul li a").click(function(e) { 
    e.preventDefault(); 
    $("#image-container img").attr('src', 'images/'+ this.hash.substring(1) +'.jpg'); 
}); 

You can try it out here,从原来的几个变化:

  • 附加处理程序为<a>,它具有散列
  • 您可以绑定同样的处理程序的许多元素,只需要使用所有抓取的元素选择你想
  • 获取具有this因为this<a>元素
  • <ul>没有id="ul"属性,因此选择应是ul,不#ul
  • 不要使用.load()这是获取内容时,src如果<img>使用.attr(),而不是设置。
+0

+1免费代码审查... – tpow 2010-10-17 16:53:52