jquery selector: reference class inside of where i

2019-01-29 01:19发布

问题:

i have this html:

<div class="title"><img class="arrow" src="rightarrow.gif" />Title</div>

i have this click event:

    $(document).ready(function () {
        $('.title').live('click', function () {

            //NEED SOMETHING HERE TO CHANGE SOURCE                 
            $(".arrow").attr("src", "downarrow.gif");
        });
    });

as you can see i want to change the src attribute of the image. my selector above works, but there are other items on the page with class ="arrow", so i need a way to just select this one instance.

回答1:

Use .find() to constrain the selector to only find elements contained within the element that was clicked (represented by $(this)):

$(document).ready(function() {
    $('.title').live('click', function() {
        $(this).find('.arrow').attr('src', 'downarrow.gif');
    });
});


回答2:

Replace with this:

$(".arrow").attr({"src": "downarrow.gif"});