2011-01-21 81 views
1

好了,所以我在重新创建此功能的过程:jQuery的新手,需要一点点帮助

http://www.w3.org/html/logo/#the-technology

我现在有它,所以当你点击一个链接,它会添加一个类与该链接相关的图像(<a>上的href =“#1”,然后在<img>上的id =“#1”),但是它目前不会经历每个<a>标签并且只有一个。而且它也不会删除我要求的班级。

代码如下:

JS

$(document).ready(function() { 

var container = '#portfolio #text_container'; 

var img_container = '#portfolio #image_container'; 

$(container).children('a').bind('click', function() { 

var this_attr = $(this).attr('href'); 

var this_img = $(img_container).find('img').attr('id'); 

if(this_attr == this_img) { 

    //$(img_container).find('img').hasClass('current').removeClass('current'); 

     // ^^^ This line isn't working, any ideas? :/ 

    $(img_container + ' img[id*="' + this_attr + '"]').addClass('current'); 

} 

else { 

    alert(this_img + ' this img'); 

     alert(this_attr + ' this attr'); 

} 

    }); 

}); 

和HTML如下

<div id="portfolio"> 

    <div id="image_container"> 
     <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" /> 
     <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" /> 
    </div> 

    <div id="text_container"> 
     <a href="#one" class="link">Item 1</a> 
     <a href="#two" class="link">Item 2</a> 

     <p id="#one" class="current">A bunch of text!</p> 
     <p id="#two">The second bunch of text!</p> 
    </div> 

</div> 

请让我知道如果你需要任何更多信息:)

rcravens fi用下面的代码固定的这个..

JS

$(document).ready(function() { 


    $('#text_container a').click(function(evt) { 
     evt.preventDefault(); 

     $('.current').removeClass('current'); 

     var href = $(this).attr('href'); 

     $("." + href).addClass('current'); 


    }); 

和HTML ..

<div id="portfolio"> 

    <div id="image_container"> 
     <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" /> 
     <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" /> 
    </div> 

    <div id="text_container"> 
     <a href="one" class="link">Item 1</a> 
     <a href="two" class="link">Item 2</a> 

     <p class="one current">A bunch of text!</p> 
     <p class="two">The second bunch of text!</p> 
    </div> 

</div> 
+0

在这里你可以看到一篇不错的文章,说明[id和classes之间的区别](http://css-tricks.com/the-difference-between-id-and-class/) – Trufa 2011-01-21 20:10:11

回答

1

我的你正在尝试做的解释是在这里:

http://jsfiddle.net/rcravens/wMhEC/

代码有点改变。你不应该有多个具有相同ID的元素。

鲍勃

+0

哇,这很简单:x是的,这正是我想要的 - 谢谢! :) – 2011-01-21 20:03:18

0

这是不工作的原因:

if(this_attr == this_img) 

是因为this_attr是一个URL,this_img是一个ID属性值。