开发者

Object-Oriented jQuery Question

$("#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!


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.


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.


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.


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();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜