Jquery 如何仅在第一次匹配时预编选择器?

Jquery 如何仅在第一次匹配时预编选择器?,jquery,media-queries,enquire.js,Jquery,Media Queries,Enquire.js,使用媒体查询,我创建了一个折叠的导航栏,而我的徽标位于底部。我用enquire.js为最后一个li做了准备。如何仅在第一个匹配上执行prepend以防止将一个li切换到右侧 prependLogo : function() { query = "screen and (max-width: 979px)"; handler = { match: function() { $(.nav

使用媒体查询,我创建了一个折叠的导航栏,而我的徽标位于底部。我用enquire.js为最后一个li做了准备。如何仅在第一个匹配上执行prepend以防止将一个li切换到右侧

prependLogo : function() {

        query = "screen and (max-width: 979px)";
            handler = {
                match: function() {
                    $(.nav-collapse .nav).prepend($("li:last"));
                },

                unmatch : function() {

                },
            };

            enquire.register(query, handler);
    },

处理这个问题有两种方法。一种是使用Inquire的
取消注册
方法。另一个是使用
设置
回调和
延迟设置
标志

设置
回调只调用一次。通常,在注册查询时会立即调用它,但与
deferSetup
标志相结合,setup会延迟到查询第一次匹配为止(不幸的是,inquire希望总是有
match
回调,因此我们将为此提供一个空函数):

unregister
方法的作用与您预期的一样,即取消查询的注册。如果我们在match回调中调用
unregister
,我们也可以实现相同的效果:

enquire.register("screen and (max-width: 979px)", {
  match : function() {
    $(.nav-collapse .nav).prepend($("li:last"));
    //note this unregisters *all* handlers for this mq (if you have more than one) 
    enquire.unregister("screen and (max-width: 979px)"); 
  }
});
下面是一个工作示例,显示了两种方法:

另外,请注意,在上面的代码中,您没有使用
var
关键字初始化变量。这在JS中是一种不好的做法,因为任何未声明
var
的变量都会附加到全局范围,这可能不是您想要的:)

enquire.register("screen and (max-width: 979px)", {
  match : function() {
    $(.nav-collapse .nav).prepend($("li:last"));
    //note this unregisters *all* handlers for this mq (if you have more than one) 
    enquire.unregister("screen and (max-width: 979px)"); 
  }
});