jQuery在单击索引值时切换DIV并在单击的DIV索引处更改图像

时间:2012-11-07 20:58:39

标签: jquery html

我有一个项目,我正在显示一个div数组。当我单击一个div时,它的索引值为0,1,2,... n将从单击的div中显示一个下拉菜单。我将它设置为当单击div时显示下拉列表并且div中包含的图像将改变(例如,如(+)到( - )图像),从而指示div被打开。我编写了一个响应,所以我知道点击的div的索引值,我在<span>显示,(这只是为了帮助我在调试时看到索引值。)当我单击div时图像将改变相应的div,但问题是无论我点击什么div,索引值(0)的div是唯一一个下拉显示我的菜单。我希望点击的div更改图像(工作)并显示菜单(损坏,索引(0)除外。

CSS

   .hidden { display: none; }  

HTML

   <div class="geolink-bar">
       <div id="arrow">
           <img src="https://geoto.s3.amazonaws.com/images/arrow_down.png">
       </div>
   </div>
   <div id="dropdown-mobile-account" class="hidden">
       <div>Display after geolink-bar is clicked</div>
   </div>
   <span></span>

SCRIPT

   $(document).ready( function() {
       $('.geolink-bar').click(function(){
           var index = $('.geolink-bar').index(this);
           $("span").text("That was div index #" + index);//DISPLAYS INDEX NUMBER F DIV CLICKED     
           $('#dropdown-mobile-account').slideToggle("slow");
           $(this).html(function(i,html) {
              if (html.indexOf('Show') != -1 ){
                  html = html.replace('Show','Hide');
              } else {
              html = html.replace('Hide','Show');
              }
              return html;
           }).find('img').attr('src',function(i,src){
           return (src.indexOf('arrow_down.png') != -1)? 'https://geoto.s3.amazonaws.com/images/arrow_open.png' :'https://geoto.s3.amazonaws.com/images/arrow_down.png';
           });
       }); 
   });

2 个答案:

答案 0 :(得分:1)

jsBin demo

CSS:

.dropdown-mobile-account{
    display:none;
}

HTML:

   <div class="geolink-bar">
     <span class="tog-txt">Show</span>
       <div class="arrow">
           <img src="https://geoto.s3.amazonaws.com/images/arrow_down.png">
       </div>
   </div>
   <div class="dropdown-mobile-account">
       <div>Display after geolink-bar is clicked</div>
   </div>

jQuery的:

$('.geolink-bar').click(function() {

      var visible = $(this).next('.dropdown-mobile-account').is(':visible'),
         slideTog = visible?'slideUp':'slideDown',
              txt = visible?'Show':'Hide',
           arrUrl = ['https://geoto.s3.amazonaws.com/images/arrow_down.png', 'https://geoto.s3.amazonaws.com/images/arrow_open.png'],
            arrow = visible? arrUrl[0] : arrUrl[1];

      $('.dropdown-mobile-account').slideUp();
      $('span.tog-txt').text('Show');
      $('.arrow').find('img').attr('src', arrUrl[0] );

      $(this).find('span.tog-txt').text( txt ).end().find('img').attr('src', arrow).end().next('.dropdown-mobile-account')[slideTog]();

}); 

答案 1 :(得分:0)

感谢“nnnnnn”的评论,我替换了我的

    $('#dropdown-mobile-account').slideToggle("slow"); 

    $(this).next().slideToggle("slow");

“RoXon”的例子是一个非常好的演示来看看@。 : - )