开发者

jQuery: Can't find a tag under only the current class selector

I have this:

HTML:

<p class="Link"><a href="...">Test1</a></p>
<p class="Link"><a href="...">Test2</a></p>
<p class="Link"><a href="...">Test3</a></p>

jQuery

$(document).ready(function() {
    $('.Link').hover(function() {
        $('.Link a').css('color', 'black');
    }, function() {
        $('.Link a').css('color', 'white');
    });
});

First of all, I need to change the anchor color when the mouse hovers over the paragraph, not just the anchor. Secondly, I need to do th开发者_Python百科is without creating a unique id for each paragraph or anchor. With the code as it is, it changes the color for all three anchors tags. I only want it to change the color on the anchor contained within the paragraph I am currently hovering over. Is this possible?

Thanks!


You need to use this which refers to the specific element that received the event.

$(document).ready(function() {
    $('.Link').hover(function() {
             // Get the <a> element from within the context of
             //    the element that received the event, represented
             //    by "this" 
        $('a',this).css('color', 'black');
    }, function() {
        $('a',this).css('color', 'white');
    });
});

Doing:

$('a',this).css('color', 'black');

is effectively the same as doing:

$(this).find('a').css('color', 'black');
  • http://api.jquery.com/find/

Of course, you could always accomplish this using purely CSS.


EDIT:

If all you're doing is changing some CSS attributes, you don't really need javascript.

To use a purely CSS approach, do this:

.Link a {
    color: black;
}

.Link a:hover {
    color: white;
}

Because you're doing this on an <a> element, it is supported on IE6. Starting with IE7 (and most other browsers) you can use the same technique on other elements too.


$(this).find("a").css("color", "black");

should do the trick.

The problem is, that ".Link a" matches ALL anchors that are in a paragraph. You probably should read into CSS again with that kind of misunderstanding!


You can use the selector $(this) inside the event to quickly refer to the element which is hovered over. After that you can use .find() to find any elements inside it.

Code:

$(document).ready(function() {
    $('.Link').hover(function() {
        $(this).css('color', 'black');
        $(this).find("a").css('color', 'black');

    }, function() {
        $(this).css('color', 'white');
        $(this).find("a").css('color', 'white');
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜