如何将"this"与另一个选择器结合起来?

Kur*_*uro 1 jquery

我正在尝试编写一个选择器,this只有在它是一个锚时它才能获取对象.我希望它什么都没有,万一它不是<a>标签.

$('.link').mouseover(function(){

    $("a", this).css('color','#00F');

})
Run Code Online (Sandbox Code Playgroud)

$("a", this).css('color','#00F');不工作,但一直期望的效果,如果我只能留下this查询.我可以在示例,博客和文档中找到的所有其他选择器用于获取子对象(find() children()),组合两个选择器(带add()),或几乎任何其他东西,但我正在寻找的东西.有人可以帮忙吗?

Mat*_*att 5

您可以使用该is()方法检查是否$(this).is('a'),然后做出相应的反应;

if ($(this).is('a')) {
    $(this).css('color', '#00F');
}
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,或许更好的解决方案是使用该filter()方法$(this).filter('a').css('color','#00F');

要注意,filter()过滤当前的 jQuery对象; 所以$('*').filter('a')会过滤a掉allll中的元素.$('a', this)另一方面(相当于$(this).find('a'))搜索jQuery对象中与提供的选择器匹配的元素的后代.