切换一堆div也改变了链接

时间:2016-08-16 12:13:13

标签: jquery html text toggle visibility

我有一堆div,标识为以字符串开头的ID(kind =" brand")。 我想通过单击跨度内的href来切换div的可见性。我希望此链接的文字从" SHOW"更改到" HIDE"。

如果没有更改文本,该功能只是在线:

  jQuery("#" + kind + "-" + value).toggle();

但是通过文本我不能通过添加一行接一行,直到大约15行代码。当然它比这简单得多。

更新了代码

            function show_hide(brand, value){
                var show_hide_text = ["SHOW", "HIDE"];
                var id_selected = jQuery("#" + brand + "-" + value).attr("id");
                jQuery('div[id ^= "' + brand + '"]').each(function() {
                    if(this.id != id_selected){
                        jQuery(this).hide();
                        jQuery("#" + this.id.replace("-", "-show-")).html(show_hide_text[0]);
                    }else{
                        var visi = (jQuery("#" + brand + "-show-" + value).html() == show_hide_text[0]) ? 1 : 0;
                        jQuery("#" + brand + "-show-" + value).html(show_hide_text[visi]);
                    } // if
                });
                jQuery("#" + brand + "-" + value).toggle();
            } // function

HTML代码就像这样(只显示一个div):

    <div ><h3 >SUPER BRAND <a href="javascript: void(0);" onClick="hide_show('brand', 'Super-brand');"><span id=brand-show-Super-brand">SHOW</a></span></h3>
      <div class="brand" id="brand-Super-brand">
            <div>PRODUCT #1</div>
       </div>
  </div>

    <div ><h3 >MEGA BRAND <a href="javascript: void(0);" onClick="hide_show('brand', 'Mega-brand');"><span id=brand-show-Mega-brand">SHOW</a></span></h3>
        <div class="brand" id="brand-Mega-brand">
          <div>PRODUCT #3</div>
        </div>
     </div>

...

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解正确,但这是代码。 HTML也有所改变。

&#13;
&#13;
$(document).ready(function(){
  var show_hide_text = ["SHOW", "HIDE"];
  $('.show-hide-content').hide();
  $('.show-hide-toggle').on('click', function(e) {
    e.preventDefault();
    var $content = $(this).parent().next('.show-hide-content');
    $('.show-hide-content').not($content).hide().prev().children('a').text(show_hide_text[0]);
    $content.toggle();	// Toggle visible
    $(this).text(show_hide_text[+$content.is(':visible')]);	// Change text
  });
});
&#13;
<!doctype html>
<html>
  <head>
    <title>StackOverflow Testing Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  </head>
  <body>
    <div>
      <h3>SUPER BRAND <a href="#" id="brand-show-Mega-brand" class="show-hide-toggle">SHOW</a></h3>
      <div class="brand show-hide-content" id="brand-Super-brand">
        <div>PRODUCT #1</div>
      </div>
    </div>

    <div>
      <h3>MEGA BRAND <a href="#" id="brand-show-Mega-brand" class="show-hide-toggle">SHOW</a></h3>
      <div class="brand show-hide-content" id="brand-Mega-brand">
        <div>PRODUCT #3</div>
      </div>
    </div>
  </body>
</html>
&#13;
&#13;
&#13;