0

有没有办法在“文档”之外的其他上下文中运行一组侦听器?

这将是限制选择器的好方法。

像这样的东西:

$(".main", function(){
   $(".child-1").click(function() {  /* .... */ });  // .main .child
   $(".child-2").click(function() {  /* .... */ });  // .main .child-2
   $(".child-3").click(function() {  /* .... */ });  // .main .child-3
});

代替:

$(".main .child-1").click(function() {  /* .... */ });  // .main .child
$(".main .child-2").click(function() {  /* .... */ });  // .main .child-2
$(".main .child-3").click(function() {  /* .... */ });  // .main .child-3

通过使用它,您可以使用范围而不是一个大(文档)范围。

那么,这些以某种方式存在于 jQuery 中?试过google,真的找不到任何东西。。

4

2 回答 2

2

最接近的事情是这样的

var $ctx = $('#context');

$ctx.find('.something').click(function(){ });
于 2013-01-21T13:53:30.303 回答
-1
$('.main').on("click", ".child-1", function() {

}).on("click",".child-2", function() {

}).on("click",".child-3", function() {

});

或者,如果他们都这样做......

$('.main').on("click", ".child-1, .child-2, .child-3", function() {

});

http://jsperf.com/on-click-performance - 你会看到这种方式比其他解决方案更快。

于 2013-01-21T13:53:21.467 回答