将jquery选择器应用于与悬停相对应的对象

时间:2011-09-25 03:45:19

标签: jquery jquery-selectors

由于某些原因,最后一行的.add无法正常工作,文档中的所有:first-child都会被修改,我只希望来自悬停对象的:first-child改性。我尝试了所有我能想到的,不知道问题是什么。

jQuery.fn.img=function(background,param,repeat)
    { $(this).css('background-image','url(/static/img/'+background+'.png')
             .css('background-repeat',repeat)
             .css('background-position',param+' top');}

$('#sliding-door li').hover(function(e)
{$(this).img('b1_middle_focus','left','repeat-x');
 $(this).add(':first-child span').img('b1_left_focus','left','no-repeat');},

html:

<ul>
          <li><a href="/href1"><span><span>Something</span></span></a></li>
          <li><a href="/href2"><span><span>Another thing</span></span></a></li>
 </ul>

1 个答案:

答案 0 :(得分:1)

<强>更新

我看到你现在要做的事情。如果您仍然需要将悬停函数应用于所有li,那么在测试第一个子节点时,您只需使用一个子语句:

$('#sliding-door li').hover(function(e) {
    $(this).img('b1_middle_focus','left','repeat-x');

    if ($(this).is(':first-child')) {
        $(this).find('span').img('b1_left_focus','left','no-repeat');
    }
}, ...);

旧答案,忽略

如果您在span的第一个孩子中寻找$(this),那么您打算使用$(this).find()而不是$(this).add()

$(this).find(':first-child span').img('b1_left_focus','left','no-repeat');

.add()将文档级别:first-child span选择器匹配的所有元素添加到$(this)对象,这与您期望的不完全相同。请参阅jQuery文档:http://api.jquery.com/add