开发者

Why won't the closest() selector work in this instance?

开发者 https://www.devze.com 2023-03-11 01:14 出处:网络
I am trying to activate toggleClass() on a specific image when clicking on a radio button. I have been trying for ages to get it to work but can\'t. I can manage to select a parent element of the radi

I am trying to activate toggleClass() on a specific image when clicking on a radio button. I have been trying for ages to get it to work but can't. I can manage to select a parent element of the radio button but nothing proceeding it. I have tried next(), nextAll() and closest(). All of which don't seem to do what I'm trying to achieve.

Here is my jQuery function:

$(document).ready(function() {
  $("input[type=radio]").change(function () {
    if (this.value == "AM") {
      $(this).closest('img[title="am"]').toggleClass('houdini');
    } else if (this.value == "PM") {
    alert('PM');
/*  开发者_如何学运维    Something here */
    } else {
        return false();
    }
  });
});

and my HTML:

<tr>
    <td><input type="radio" name="bisley" value="AM" />AM<input type="radio" name="bisley" value="PM" />PM<span class="compname">Bisley</span></td>
    <td>Fit more into less space</td>
    <td class="time"><img src="/images/generic/openday/tick.png" alt="tick" title="am" class="houdini" />10.00AM</td>
    <td class="time"><img src="/images/generic/openday/tick.png" alt="tick" title="pm" class="houdini" />1.30PM</td>
</tr>


closest searches ancestor elements; next and nextAll search sibling elements. The img element you want is the child of a sibling element, so you'll need a more complex statement. Have a go with this:

$(this).closest('tr').find('img[title="am"]').toggleClass('houdini');

This says "find the closest ancestor tr element, then find img[title="am"] within that.


change to

$(this).parent().children('img[title="am"]').toggleClass('houdini');

SEE DEMO

0

精彩评论

暂无评论...
验证码 换一张
取 消