在jQuery中编写更好的选择器

时间:2011-04-08 20:05:47

标签: javascript jquery

编写以下选择器的最佳方法是什么?

id = "#id",
$id = $("#id");
//works but seems wrong    
$($id, 'a').click(function(){
 //do stuff..
});

//this was not working for me.
$id.find('a').click(function(){
 // do stuff...
});

3 个答案:

答案 0 :(得分:4)

较短查找的正确语法是:

$('a', $id).click(function(){
 //do stuff..
});

这会在$id

中找到所有锚标记

将它与find fn:

一起使用
$id.find('a').click(function(){
 // do stuff...
});

这一切都假设你的标记是这样的:

<div id='id'> //div or any other html element
    ... any code
    <a href.... ></a> << the anchor can be anywhere inside this div
</div>

答案 1 :(得分:1)

上下文is the second argument,而不是第一个。

$('a', '#id').click(function(){
 //do stuff..
});

答案 2 :(得分:0)

$("#id a").click(function() {} );

$("#id > a").click(function() {} );
相关问题