HTML:

<div class="buttons"> <button>Boston</button> <button>Acapulco</button> </div> <div class="tables"> <img src="images/boston.jpg" id="image1"> <img src="images/acapulco.jpg" id="image2"> </div> 

It is necessary that by clicking on the button you get 1 picture corresponding to the button. How to do this with this, so as not to write a separate code for each picture, if there are 100?

The maximum that I got (but still wrong):

 $('button').on('click', function(){ $((this).'img').css('display','block'); }); 
  • Take out the image in the img tag as a separate attribute. Then get the text from the button and find the desired img. Any methods not related to the clear identification of the object to be influenced seem to be crutches. - GlWhitefoot

1 answer 1

I suspect they wanted something like this:

 $('button').on('click', function(){ var idx = $(this).index(); $('.tables img:eq(' + idx + ')').show(); // $('.tables img[id=image' + (++idx) + ']').show(); }); 
 .tables img { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="buttons"> <button>Boston</button> <button>Acapulco</button> </div> <div class="tables"> <img src="http://1.bp.blogspot.com/-rIH-NcvXJTk/TVRv2_xk9rI/AAAAAAAAANE/AVGEB-arWXk/s1600/images.jpg" id="image1"> <img src="https://i.mycdn.me/image?id=605295869202&t=0&plc=WEB&tkn=*X-f02Q2b_3NyhFEHYNv-jfbAsmg" id="image2"> </div> 

That is, each button index corresponds to the image index. True, if the indices do not correspond exactly in parallel, then another strategy should be applied.

In this case, use index () to get the number of an element in the collection and eq to extract at a given index from another.

  • Can you clarify, please, 2 things: 1. How is the picture displayed, if in css display: none? 2. part of the expression ('+ idx +') - what is it? Nowhere can I find a clear explanation used + in jQuery or JS in such expressions (not in cycles or mathematical expressions - there the meaning of the + sign is clear). - Alex
  • Can you clarify, please, 2 things: - Alex
  • Как отображается картинка, если в css display:none? - the method .show() just makes the display block ..... method hide() - display none, respectively ............. .часть выражения ('+ idx+') - что это? - this is concatenation .... because the variable in quotes is interpreted as a string, then it must be removed from the string ...... and how to remove it and leave it as part of the string? concatenation, which is what pluses do - Alexey Shimansky
  • And how to make, so that when you click on any of the buttons, only one image is displayed in html, and not all the pictures alternately? Those. one button - one picture, without removing all the pictures after all the clicks of all the buttons. - Alex
  • @Alex hide all pictures, and then show only the one with the index - Alexey Shimansky