与(first)结合使用时find()和children()之间的jQuery差异 [英] jQuery difference between find() and children() when combined with :first

查看:80
本文介绍了与(first)结合使用时find()和children()之间的jQuery差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答以下jQuery问题的过程中需要有关优化以下jquery代码的帮助,我偶然发现了另一个问题大约.find().children().

In the process of answering the following jQuery question Need help in Optimizing the below jquery code , I stumbled across another question about .find() and .children().

问题是,给了四个ID为城市分支分支地址的选择框,以将其删除除了每个选择框的第一个选项以外的所有选项.

The question was, given four selectboxes with ids state, city, branch, branchAddress, to remove all but the first option for each select boxes.

已经发布了几个答案.其中有:

There has been several answers posted. Among those were :

  1. $('#state,#city,#branch,#branchAddress').children('option:not(:first)').remove();
  2. $('#state,#city,#branch,#branchAddress').children('option:not(:first-child)').remove();
  3. $('#state,#city,#branch,#branchAddress').find('option:not(:first)').remove();
  1. $('#state,#city,#branch,#branchAddress').children('option:not(:first)').remove();
  2. $('#state,#city,#branch,#branchAddress').children('option:not(:first-child)').remove();
  3. $('#state,#city,#branch,#branchAddress').find('option:not(:first)').remove();

根据此js小提琴( http://jsfiddle.net/QkNRf/1/)

解决方案2和3似乎运行良好.

Solution 2 and 3 seem to work perfectly.

如果有人可以指出我错过的内容,或者向我解释为什么解决方案3在解决方案1无效的地方工作,我会很高兴.

I would be glad if someone could point me what I missed, or explain to me why solution 3 works where solution 1 does not.

推荐答案

所有其他答案都是正确的,但我认为文档中解释示例1为何失败以及数字3为何起作用的重要部分是有效地.children()过滤前一个选择器的结果,.find()将执行选择器上下文搜索,因此(我假设)它将在所有4个上下文中执行'option:not(:first)'搜索并整理结果,而.children()首先将整理结果,然后使用'option:not(:first)'进行过滤,从而有效地去除了除第一个以外的所有内容...

All the other answers are correct but I think the important part in the doc that explains why example 1 fails and why number 3 works is that while .children() effectively filters the results from the previous selector, .find() will perform selector-context search, so (I assume) it will perform the 'option:not(:first)' search in all 4 contexts and collate the results, while .children() will first collate the results and then filter using 'option:not(:first)' effectively removing all but the very first...

在这种情况下,搜索的深度无关紧要.

The depth of search is irrelevant in this case.

这篇关于与(first)结合使用时find()和children()之间的jQuery差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆