我有一种情况,我所有的选择器都有相同的祖先元素
$('#foo .bar')...
$('#foo .some_class')...
$('#foo .some_other_class')...
我想知道是否有办法告诉 jQuery 始终假定选择器将派生自 #foo
?所以像
$.ancestorWillAlwaysBe('#foo');
$('.bar')...
$('.some_class')...
$('.some_other_class')...
最佳答案
看起来你懒得输入那些#foo
。这是一种更简单的方法:
var e = $("#foo"); //short enough
$('.bar', e);
$('.some_class', e);
$('.some_other_class', e);
或者如果你真的那么懒惰,你可以这样做:
$ = function(que, anc){
if($.ancestor){
return jQuery(que, $.ancestor);
}else{
return jQuery(que, anc);
}
}
$.ancestor = "#foo"; //Ancestor will now always be #foo
$('.bar')...
$('.some_class')...
$('.some_other_class')...
$.ancestor = undefined; //Clear
关于javascript - jQuery 为作用域设置祖先元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171957/