How to filter images by category using input form

2019-08-30 09:06发布

问题:

For example

I have a page where there are 4 images

<img src="1" />

<img src="2" />

<img src="3" />

<img src="4" />

Filter:
<form>
<input type="checkbox" name="gallery" value="abstract" /> Abstract<br />
<input type="checkbox" name="gallery" value="landscape" /> Landscape
</form> 

How can I add some markup each image to be part of a certain category, then using a checkbox to filter them with jquery .hide()? I'd prefer not using the class attribute. Thanks a lot for the huge help!

回答1:

For type add a certain class (even if you do not want to...)

$('input[value="landscape"]').click(function(){
    $('.landClass').toggle();
});

$('input[value="abstract"]').click(function(){
    $('.absClass').toggle();
});

Fiddle: http://jsfiddle.net/maniator/3bk22/



回答2:

Try this

<div id="abstract">
   <img src="1" />

   <img src="2" />
</div>

<div id="landscape">
   <img src="3" />

   <img src="4" />
</div>

$("input:checkbox").click(function(){
  $("#abstract, #landscape").hide();
  if($(this).is(":checked")){
     $("#"+$(this).val()).show();
  }
});


回答3:

You may use the attribute alt of img

<img src="1" alt="abstract"/>

and jquery:

$(document).ready(function(){
    $('input[name="abstract"]').click(function(){
       $('img[alt="abstract"]').toggle();
})

     $('input[name="landscape"]').click(function(){
       $('img[alt="abstract"]').toggle();
})

});


回答4:

Try this: http://jsfiddle.net/shaneburgess/wTkR5/6/

$(document).ready(function(){

    $("#abstractCheck").change(function(){
       $(".abstract").toggle();
    });

     $("#landScapeCheck").change(function(){
       $(".landscape").toggle();
    });

});

HTML:

   <span class="abstract">
    <img src="1"/>
</span>

<span class="landscape">
   <img src="2" />
</span>

<span class="abstract">
   <img src="3" />
</span>

<span class="landscape">
   <img src="4" />
</span>