开发者

Telling jQuery which (unique) div to do an action on

My plan is to have lots of boxes (an undefined amount). When show box is clicked under a box, it shows that particular box.

I have some unique divs in my html. The div is made unique by:

<div id="box-<%=box.id%>"></div>

In my application.js, I have

$('.show-box > a').click(function(){
$('#box').show();
});

I obviously need to have the box-id in the $('#box').show(); part but I'm unsure how to do that...

EDIT: adding more information

<div class="show-box">
  <a href="javascript:void(0)">Show</a>
</div>

<div class="box" id="box-<%= box.id  %>"></div>

The class is for styling.

Just to add, I know that the javascript link should link to an actual 开发者_如何转开发link. I'll fix that later.


You would use this inside the handler to refer to the specific .show-box > a that was clicked.

So it depends on what the relationship is between that and the box element you want to display.

When you say under, if that means that it is a sibling to the .show-box element, you can use .parent() to traverse up from the <a>, then use .prev() to traverse back to the box.

$('.show-box > a').click(function() {
      // "this" refers to the <a> that was clicked.
    $(this).parent().prev().show();
});

Ultimately, the correct solution depends on your actual HTML markup. If you provide that in your question, it would be helpful.

You could select by ID if you want, but it is often not necessary.


On easy way would be to name your box ids after you a ids, or write another attribute into the a. For example if your a tag's ID was "anchor1", assign the corresponding div an id of "box-anchor1". Then, reference it like this:

$('.show-box > a').click(function(){ 
$('#box' + this.attr('id')).show(); 
}); 


If the box and the link that shows it are logically related, you can skip the whole unique ID business by using the following:

HTML

<div class="container">
  <div class="box">
    <!-- stuff in the box -->
  </div>
  <a href="#">Show</a>
</div>

jQuery

$("div.container a").click(function() {
  $(this).prev().show(); // prev() will get the div.box element.
});

On the other hand, if they are not related structurally, you can use the fragment part of the URL to reference the box ID:

HTML

<div>
    <div class="box" id="box-1">...</div>
    <div class="box" id="box-2">...</div>
</div>

<div>
    <a class="boxtoggler" href="#box-1">Show Box 1</a>
    <a class="boxtoggler" href="#box-2">Show Box 2</a>
</div>

jQuery

$("a.boxtoggler").click(function() {
    var boxId = $(this).attr("href");
    $(boxId).show();
});

Note how we're abusing the fact that the fragment section of a URL is preceded by a # character to make it into a css ID ;)


Not sure I understood your question, but if you want to show the clicked box:

$('.show-box > a').click(function(){
$(this).parents('.show-box').show();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜