Using jQuery, how do you select another element based on the clicked element?

It's hard to tell this as a question in one small headline.

Basically, I have a div:

<div class="sites" id="site1"></div>

which can be clicked by the user, and when this div is clicked, I want another div to appear with a similar identifier:

<div id="site1_desc" class="description_holder">

Is there a way that when the previous div is clicked can be selected last for use. I have the same div combination for site2, 3, 4, etc. I thought something like:

$(document).ready(function(){
   $('.sites).click(function(){
      $(this&'_desc').css({visibility: "visible"});
     });
});

I understand that the above does not work, but I am not sure what the best way to do this. Hopefully now the question is clearer.

+4
source share
4 answers

Using:

$(document).ready(function(){
 $('.sites').click(function(){
   $('#'+$(this).attr('id')+'_desc').css({visibility: "visible"});
 });
});

Working script

+2
source

this.id , . "_desc". # id .

$(document).ready(function(){
   $('.sites').click(function(){
      $("#" + this.id + '_desc').css({visibility: "visible"});
     });
});
+1

You can use this.idto get the id of the clicked item. Also, you are missing a quote in the selector and need to put #in front of the identifier selector.

$(document).ready(function(){
   $('.sites').click(function(){
   //.......^..................
      $('#'+this.id+'_desc').css({visibility: "visible"});
     //....^....^..........
     });
});

+ can be used for concatenation

+1
source

Specify the target in the data attribute on the clicked element:

<div class="sites" id="site1" data-target='site1_desc'></div>

$(document).ready(function(){
    $('[data-target]').on('click', function(){
        $('[data-target=' + $(this).data('target') + ']').show();
    }
});

... then it applies to any element that has data-target. This template is used in many popular front-end frameworks; for example, twitter boot menus.

+1
source

Source: https://habr.com/ru/post/1524226/


All Articles