Ton*_*bet 4 jquery events css-selectors custom-exceptions
假设我想绑定所有项目
#mainDiv .user
Run Code Online (Sandbox Code Playgroud)
除了
#mainDiv #exception .user
Run Code Online (Sandbox Code Playgroud)
我能想到
$('#mainDiv .user').bind('event',function(){
if($(this).parents('#exception').length>0){}else{
// do stuff;
}
});
Run Code Online (Sandbox Code Playgroud)
要么:
$('#mainDiv :not('#exception').find('.user').bind('event',function(){
if($(this).parents('#exception').length>0){}else{
// do stuff;
}
});
Run Code Online (Sandbox Code Playgroud)
什么是更好的?
Ben*_*den 14
我可能会建议改为
$('#mainDiv .user').not('#mainDiv #exception .user').bind('event',function()
{
//do stuff
});
Run Code Online (Sandbox Code Playgroud)
not()函数接受以前存在的jquery集,并从中删除符合作为参数传入的选择器的元素.
预先过滤池比使用选择器和if语句更清晰,更高效(可能无关紧要,但这是一个好习惯),一旦你过滤了if语句就不必要了.
作为附注,过滤"#mainDiv #exception .user"对我来说似乎有些奇怪."#exception"应该是一个唯一的标识符 - 除非你担心由于某种原因"#mainDiv"可能是"#exception"的孩子.
| 归档时间: |
|
| 查看次数: |
6701 次 |
| 最近记录: |