如何告诉jQuery停止搜索DOM

如何告诉jQuery停止搜索DOM

本文介绍了找到第一个元素后,如何告诉jQuery停止搜索DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

据我了解,在查询中添加.first():first不会在第一个匹配项后停止DOM搜索.它只是告诉jQuery从匹配的集合中取出第一个元素.

From what I understand, adding .first() or :first to a query doesn't stop DOM search after the first match. It just tells jQuery to take 1st element out of matched collection.

如果是这样,那么有没有办法在第一个匹配项之后停止DOM搜索?例如,如果我知道此查询的结果将始终是单个元素,那么如何告诉jQuery不要浪费时间进行进一步的搜索?

If that is true, then is there a way to stop DOM search after the first match? For example, if I know that the result of this query will always be a single element, how can jQuery be told to not waste time searching further?

推荐答案

据我所知,目前尚无法在jQuery中进行此操作.最好的方法是$(selector).first(),其中selector是标准CSS选择器,不包括任何Sizzle特定的选择器(因此请不要使用:first).在这种情况下,jQuery在现代浏览器中使用快速DOM querySelectorAll方法.

As far as I know there's no way to do this in jQuery at the moment. The best you can do is $(selector).first(), where selector is a standard CSS selector not including any Sizzle-specific selectors (so don't use :first). In this case jQuery uses the fast DOM querySelectorAll method in modern browsers.

您可以使用DOM querySelector方法手动获得优化,该方法被构建为仅选择第一个匹配项:

You can get the optimisation manually by using the DOM querySelector method which is built to select only the first match:

$.getFirst= function(selector) {
    if ('querySelector' in document)
        return $(document.querySelector(selector));
    else
        return $(selector).first();
}

但是,这样做所节省的金额要比确保使用querySelectorAll所节省的金额小得多.

however the amount you'll save by doing this is much smaller than the amount you save by making sure querySelectorAll can be used.

这篇关于找到第一个元素后,如何告诉jQuery停止搜索DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:13