【问题标题】:jquery selector performancejQuery选择器性能
【发布时间】:2011-06-23 06:57:12
【问题描述】:

有没有更高效的方法来写这个。

$('#test').find('option:selected[value!=""]')

【问题讨论】:

  • 完全没有,只是想看看有没有更好的写法。

标签: jquery performance jquery-selectors


【解决方案1】:

您可以稍微调整一下,但使用方法而不是 Sizzle:

$('#test').find('option').filter(function() {
    return this.selected && this.value.length
});

基准测试http://jsperf.com/sizzle-vs-methods-filter/12

.filter() 对我来说快了大约 70%。

【讨论】:

  • 我试过this.selected && this.value.length,Console.log给出的是jquery()而不是值。
  • @alex:哎呀,我忘记了return statement,请参阅更新。对不起。
  • @jAndy,你能重新运行包含返回语句的基准测试吗?我很想知道它是否会影响结果。
  • @ar:我也更新了基准,确实不影响性能。
  • @jandy,谢谢,我发帖后发现退货不见了。
【解决方案2】:

嗯,总是只有一个被选中,所以我认为你不需要find() 处理程序。

我就这样写吧:

$('#test option:selected[value!=""]')

我还没有测试过。

【讨论】:

  • 使用 jsperf.com 会比 find 慢 2% 的结果。使用过滤器是要走的路。
猜你喜欢
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2012-05-15
相关资源
最近更新 更多