1

So let's say I have multiple div's on a page with the ID of "Toggle". and in every div there are two other divs.

  1. "Headline" This is always visible.
  2. "Comment" This toggles on/off when the headline is clicked on (default is off).

How would I do this with jquery? I got it working, but only with one on the page.

<script>
    $(function() {
        $('#toggle').on('click', function () {
          $(this).find('#comment').slideToggle(100);
        });
    });
</script>

(perhaps this is another question, but I would also like the "headline" div's background to be changed to blue when it is clicked (and the comment is dropped down) and revert when "headline" is clicked again, sliding the comments up)

4

2 回答 2

1

Like I said in my comment above, jQuery targeting will fail (or at the very least not behave as expected) if use an ID more than once. Use classes for styling and targeting in this case, or use unique IDs per 'toggle' module.

Alright, here's your Codepen example :)

Core components [expanded styling available in Codepen sketch]

HTML

<div class='toggle'>
  <h3 class='headline'>My headline</h3>
  <div class='comments'>
    <ul>
      <li>Comment 1</li>
      <li>Comment 2</li>
      <li>Comment 3</li>
    </ul>
  </div>
</div>

CSS

.comments {
  display: none;
}

.comments.open {
  display: block;
}

jQuery

$('.headline').on('click', function(){
  $(this).toggleClass('active');
  $(this).next('.comments').toggleClass('open');
});

Alternate jQuery slideToggle

$(this).next('.comments').slideToggle(); // instead of toggling a class

Hope that helps!

UPDATE:

Pure jQuery background-color toggle

var active = false;

$('.header').on('click', function(){
  if(active == false) {
    $(this).css('background-color', 'blue');
    active = true;
  } else {
    $(this).css('background-color', 'white');
    active = false;
  }
});
于 2013-08-22T01:39:42.010 回答
0

It is working with only one because you have inserted id='toggle' instead use class so it will work on all and in the case of sliding try out this http://jsfiddle.net/MohammadHamza/F64n9/'>Fiddle.

于 2013-08-22T01:50:24.000 回答