views:

122

answers:

4
$("#e1").click(function() {
  $("#descriptions div").removeClass("show");
  $("#e1d").addClass("show");
});

$("#e2").click(function() {
  $("#descriptions div").removeClass("show");
  $("#e2d").addClass("show");
});


<div id="descriptions">

<div id="e1"></div>
<div id="e1d" class="description"></div>

<div id="e2"></div>
<div id="e2d" class="description"></div>

</div>

I'm trying to figure out a way to not to repeat the code and have jQuery automatically search and link the divs. So it'd be wonderful to link every id with the name e1~∞ to e1~∞d. Not sure how to implement the proper Object-Oriented methodology. Thank you for reading!

+3  A: 

Something like this may work:

$("id^='e'").click(function() {
    $("#descriptions div").removeClass("show");
    $("#" + $(this).attr("id") + "d").addClass("show");
});

The expression "id^='e'" selects all elements for which the id starts with e. So as you see e1 is not a very good name... Rather take something more descriptive.

But even stronger, if e refers to multiple elements, why don't you make a class name e like so?

<div id="descriptions">
    <div id="e1" class="e"></div>
    <div id="e1d" class="description"></div>

    <div id="e2" class="e"></div>
    <div id="e2d" class="description"></div>
</div>

jQuery is then easier to read and understand.

Paul
I suggest using also `$("#descriptions div.show").removeClass("show");` instead of `$("#descriptions div").removeClass("show");`
Alex Bagnolini
$(this) works directly, so you don't have to call the selector twice
rmontagud
Making a class is indeed a better way to do it. When I see a string concatenation in a selector, I look for a way to restructure it more cleanly.
cobbal
A: 

You could use jQuery Regex Filter and use simple regex to bind the click event. Although I would go with different IDs that would make Paul's answer possible.

Marek Karbarz
A: 

you could define your function to the jQuery object to handle this.

$.fn.toggleShow = function(){
     $("#descriptions div").removeClass("show");
     $("#" + $(this).attr('id') + "d").addClass("show");  
}

$("#e1").click(function(){
     $(this).toggleShow();
});
GSto
+7  A: 

Give your elements classes and then reference them in the jQuery via class name:

<div id="descriptions">

<div id="e1" class="trigger"></div>
<div id="e1d" class="description"></div>

<div id="e2" class="trigger"></div>
<div id="e2d" class="description"></div>

</div>


$(".trigger").click(function() {
      $('#descriptions>div').removeClass("show");
      $(this)
      .next("div.description")
      .addClass("show");
});

All that said, it looks like you are wanting to show/hide divs. You might want to look into jQuery's 'toggle' for that.

DA
There's an error in your code as clearly the removeClass("show") should refer to all the other elements instead of $(this)
Paul
Paul...ah, good catch. I'll fix.
DA