在jQuery中使用过滤器

时间:2012-03-23 15:01:29

标签: javascript jquery html css

<div class="main">
    <a title="here" href="http://google.com">google.com</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a class="click" href="#">check site</a>
</div>
<div class="main">
    <a title="here" href="http://stackoverflow">stackoverflow</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a class="click" href="#">check site</a>
</div>
<div class="main">
    <a title="here" href="http://cnn.com">cnn.com</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a title="sss" href="www.sss.com">sss</a>
    <a class="click" href="#">check site</a>
</div>

我写道:

$(".click").click(function(){
  alert($(this).parent().filter("[title=here]").attr('href'));
})

但这显示我未定义。如何从当前的DIV获取当前站点?

现场:http://jsfiddle.net/uB4ez/

2 个答案:

答案 0 :(得分:7)

filter方法过滤掉结果中的特定项,您希望使用find方法在结果中查找元素的子项:

alert($(this).parent().find("[title=here]").attr('href'));

如果您拥有所有的childred并且想要保留特定的一个,则将使用filter方法。例如:

alert($(this).parent().children().filter("[title=here]").attr('href'));

答案 1 :(得分:1)

.filter()没有获得子节点。

如果您只想查看下一级子节点,请使用.children("[title=here]")

要搜索所有后代节点,请使用.find("[title=here]")