Question

I am trying to have the action done to ONLY the item clicked, but the current result is to do the action to all items on the page. Thus, I would like to only select the specific "product_image" that I click on, not every "product_image".

$('.product_image').on('click', function() {
    $('.description').toggleClass('show-description');
  });
Était-ce utile?

La solution

The key to operating only on the clicked on item or something in the same branch of HTML as the clicked on item, it to use $(this) in the click handler as the basis for your selector.

  1. If you want to target the element that was clicked on itself, then you use $(this) to get a jQuery object for that element.

  2. If what you want to target is a child of the item that was clicked on, you can use $(this).find("selector") to find the relevant child.

  3. If what you want to target is in the same branch, but not a direct child, then you use $(this).closet("common parent selector") to go up to the common parent and then .find() from there to find the item you're looking to target.

Assuming the .description element you want is inside the product_image item, then you can do this:

$('.product_image').on('click', function() {
    $(this).find('.description').toggleClass('show-description');
});

or, sometimes they have a common parent and you do something like this:

$('.product_image').on('click', function() {
    $(this).closest("common parent selector").find('.description').toggleClass('show-description');
});

If you add the relevant HTML to your question, we can advise much more specifically.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top