-1

I have eight clickable icons (pulse1, pulse2 - pulse 8) which are linked to the corresponding content (content1, content2 etc). Instead of writing the code below out each time for each is there a way I can condense it down using an increasing integer or something? Fairly new to this game!

Dev version can be seen at http://aceresponsive.webdevspace.co.uk

Many thanks.

$("#pulse1").click(function () {

  $(this).siblings(".active").removeClass("active");
  $(this).toggleClass('active');

    if ($('.purple-content').is(':visible')) {

       if ($('#content1').is(':visible')) {

           $(".purple-content").fadeOut();


       } else {

           $(".purple-content").fadeOut();

           $("#content1").fadeToggle();
       }

    } else {

       $("#content1").fadeToggle();

    }
});

which calls for:

<div class="purple-content" id="content1">
<h2>the brain</h2>

<img src="assets/img/icons/brain-dark.png" width="144" height="167" alt="The Brain"      class="alignright">
<p>Stroke … A serious medical condition that occurs when the blood supply to part of the brain is cut off. It can affect our bodily functions, thought processing, ability to learn, communication and emotions.</p>

<h3>Learn More</h3>

<ul>
 <li><a href="#">The factors that can increase risk</a></li>
 <li><a href="#">Stroke symptoms</a></li>
 <li><a href="#">Types of stroke</a></li>
</ul>

</div>
4

2 回答 2

0

您可以概括该函数,假设末尾的 ID 号pulse永远不会变成两位数:

$("[id^=pulse]").click(function () {
    var idNum = this.id.substr(this.id.length - 1, 1);
    $(this).siblings(".active").removeClass("active");
    $(this).toggleClass('active');

    if ($('.purple-content').is(':visible')) {
        if ($('#content' + idNum).is(':visible')) {
           $(".purple-content").fadeOut();
        } else {
            $(".purple-content").fadeOut();
           $("#content" + idNum).fadeToggle();
        }
    } else {
        $("#content" + idNum).fadeToggle();
    }
});
于 2013-10-15T14:50:25.690 回答
0

附加带有某种引用的 HTML,这里我给了它一个属性,您可以在单击时使用 jQuery 的方法data-收集该属性。.data()

<div class="pulse" data-contentref="1"><div>
<div class="pulse" data-contentref="2"><div>
..
<div class="pulse" data-contentref="n"><div>

<script>  
    $(".pulse").click(function () {

      var $Content = $('#content'+ $(this).data('contentref') +'');
      $(this).siblings(".active").removeClass("active");
      $(this).toggleClass('active');

        if ($('.purple-content').is(':visible')) {
           if ( $Content.is(':visible')) {
               $(".purple-content").fadeOut();
           } else {
               $(".purple-content").fadeOut();
               $Content.fadeToggle();
           }
        } else {
           $Content.fadeToggle();
        }
    });
</script>

小提琴添加:http: //jsfiddle.net/7JvFZ/3/

于 2013-10-15T14:55:05.887 回答