0

Let's say I have 10 images on a page, and I want to hide an image when clicking on it.

Each image has an id like: figure1, figure2, figure3, figure i++.

Of course I could write this

$('#figure1').on('click', function() {
    $(this).hide();
});

$('#figure2').on('click', function() {
    $(this).hide();
});

$('#figure3').on('click', function() {
    $(this).hide();
});

and so on but obviously that's not good.

The other thing I thought was creating a function and triggering it with onclick="theFunction(id)", so then I could hide the right image within the function as it knows the id of the image, but when the page loads, obviously JS doesn't know which ID I'm going to delete. How could I make this dynamic?

Any suggestions?

Err I was using class instead of ID in my function :/

function deletePhoto(photo_id, photoPosition) {
   $('#photoFigure' + photoPosition).fadeOut(2000);
}

Called like:

<div class="deletePhoto" onclick="deletePhoto({$value['id']}, {$i})">delete</div>  
4

3 回答 3

3

You can give all of them a common class name say figure and use that as the selector:

$('.figure').on('click', function() {
   $(this).hide();
});

Or with what you have you could go with attribute starts-with selector

 $('[id^="figure"]').on('click', function() {
   $(this).hide();
});

or just combine all of them and make a long and ugly selector:

 $('#figure1, #figure2, #figure3').on('click', function(){
     $(this).hide();
 });

For the second part of your question, you can remove those inline click attribute and add a data-attribute save the photoid as is there and just use it to delete, if you have a consistent html structure then you dont event need that, you can select the photo relative to the deletePhoto button.

 <div class="deletePhoto" data-photoid="#photoFigure{$i}">delete</div>

and

$('.deletePhoto').on('click', function(){
        $($(this).data('photoid')).fadeOut(2000); 
       //<-- fade out won't delete the element from DOM instead if you really want to remove then try as mentioned below.
       //$($(this).data('photoid')).fadeOut(2000, function(){$(this).remove();});
});
于 2013-10-07T03:00:17.233 回答
0

OR Could use multiple Select them like this:

Also plz note you are missing ) in your JQ code.

Link : http://api.jquery.com/multiple-selector/

Sample code

$('#figure1,#figure2,#figure2').on('click', function() {
    $(this).hide();
});
于 2013-10-07T03:01:02.543 回答
-1
$(body).on('click','img',function() {
    var fig = $(this).attr('id');
    $('#' + fig).fadeOut();
});
于 2013-10-07T03:04:40.110 回答