2

I am currently teaching myself jQuery (started yesterday) and I'm stuck already.. I have this to create small dropdowns that will work relative to each other.

$(document).ready(function(){
  var selTxt = 0;
  $(".button").click(function(){
        alert($(this).prev(".button").attr("id"));
        $(".text").slideUp(150);
        $(this).next(".text").slideToggle(150,function(){
            selTxt = $(this).prev(".button").attr("id");
        });

  });
});

Those of you that know jQuery will realise it simply expands a textbox when clicking a button and hides all others that are expanded.

Question:

Take a look and see where the alert() function is called. On that line I wish to run an if statement.. Something like this:

$(".button").click(function(){
    if($(this).attr("id") == selTxt){
        $(".text").slideUp(150);
        $(this).next(".text").slideToggle(150,function(){
            selTxt = $(this).prev(".button").attr("id");
        });
    }
});

Hence I only want it to run if selTxt doesn't equal the id of the element that has been clicked. So the $(this) in the if statement (I HOPED) would refer to the .button being clicked, but guess what: it doesn't! Could anybody inform me why not? I thought because I referenced the .button with $(this) lower down that I would be able to use it there as well but evidently not.

Good old JSFiddle here.

Thanks in advance.

4

2 回答 2

1

It does work, in your JSfiddle you've only added an ID to the first DIV element and not to all the others, therefor a UNDIFINED will show up if you try to get the ID attr from the element, so add the ids and you'll be fine.

于 2012-11-29T14:53:46.713 回答
1

As @Hawiak pointed, the problem is that your're testing .attr("id") of all div.button but your HTML has an id attribute assigned only for the first div. But at all, I don't believe checking by the id is the best way to do it. Here's my suggestion:

$(function() {
  $(".button").click(function() {
      var text = $(this).next(".text");

      if (!text.hasClass("open")) {
        $(".text").slideUp(150).removeClass("open");
        text.stop(true, true).slideToggle(150).addClass("open");
      }
  });

  $(".hideAll").click(function() {
    $(".text").slideUp(150).removeClass("open");
  });
});​

And the updated Fiddle here.

于 2012-11-29T15:00:49.843 回答