How to show images by name (prefix)

2019-08-09 17:15发布

问题:

How to show in block only images which name have some text like "small". To show only picture2_small.gif and picture4_small.gif. And in another block show all of 'em.

<div class="small_images">
  <img src="picture1.gif" />
  <img src="picture2_small.gif" />
  <img src="picture3.gif" />
  <img src="picture4_small.gif" />
</div>

<div class="all_images">
  <img src="picture1.gif" />
  <img src="picture2_small.gif" />
  <img src="picture3.gif" />
  <img src="picture4_small.gif" />
</div>

回答1:

Use one of the below selectors

img[src$='small.gif'] - to display only images whose src ends with small.gif

or

img[src*='small'] - to display only images which contain the word small in its src.

Using CSS

.small_images img[src$='small.gif']{
    display: block;
}
/* or */

.small_images img[src*='small']{
    display: block;
}

Using jQuery

$('.small_images img[src$="small.gif"]').show();
/* or */
$('.small_images img[src$="small.gif"]').css('display','block');

/* or */

$('.small_images img[src*="small"]').show();
/* or */
$('.small_images img[src*="small"]').css('display','block');

Additional Info: (based on your change to the question)

Adding .small_images would make sure that the display is set to only those img tags that are present under the element with class='small_images'.



回答2:

Try with the selector

$('img[src*="_small"]').show();


回答3:

To show the ones with small and hide the others try,

   $(document).ready(function(){
$('img').each(function(){
    var $img = $(this);
    if($img.attr("src").indexOf("small")!=-1){
        $img.show();
    }else{
        $img.hide();
    }
});});

http://jsfiddle.net/3KcYk/



回答4:

Simple;

you may use;

<div class="small_images">
<img src="picture1.gif" />
<img src="picture2_small.gif" />
<img src="picture3.gif" />
<img src="picture4_small.gif" />
</div>

and for images inside div, use styling like;

.small_images img{
    display: none;
}

Then in your javascript, show images having text like "small", you have mentioned using;

$('img[src*="small"]').show();

Here is a demo