繁体   English   中英

在jQuery中编写更好的选择器

[英]Writing better selector in 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...
});

较短查找的正确语法是:

$('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>

上下文是第二个参数 ,而不是第一个。

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

要么

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM