儿童vs选择器 - jQuery [英] children vs selector - jQuery

查看:90
本文介绍了儿童vs选择器 - jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了简单起见,我将缩小以下问题的范围。我有一个大的代码在点击js函数中运行。为了表示所有我已经添加了 alert()



HTML

 < ul> 
< li>测试李1< / li>
< li>测试李2< / li>
< li>测试李3< / li>
< li>测试李4< / li>
< li>测试李5< / li>
< / ul>

JS

方法1

  $('ul li')。click(function(){alert('hi');} ); 

方法2

  $( 'UL')儿童()点击(函数(){警报( '你好');}); 

方法1和方法2都可以正常工作。

哪一个更好?使用选择器还是使用children方法会更好吗?当我们可以使用选择器时,有一个子方法的目的是什么?



测试小提琴



我只是抓住基础知识,希望不知道某些东西不是犯罪。谢谢

解决方案

虽然这两段代码在示例HTML上正常工作,但它们并不完全相同。
$ b

.children 返回所有子元素(不管它们是否是li)。

ul li作为选择器返回ul的所有li后代,无论它们是否为子元素。



这两个是等价的,并且只选择ul父母的li子女:

  $('ul> li')。click(function(){alert('hi');}); 
$('ul')。children(li)。click(function(){alert('hi');});

至于哪一个更好(原始问题),对于这个我怀疑的问题并没有真正的答案。将取决于你的实际需求和HTML(当你问哪一个更好?你的意思是什么?性能?可维护性?)。通常情况下,前者将使用浏览器的CSS选择器引擎,其中您使用的选择器是受支持的,而后者将始终使用jquery构建的代码(我认为)在大多数情况下,我会选择前者。


For the sake of simplicity I'll narrow down the question as below. I have a large code running in the click js functions. To represent that All I have added an alert()

HTML

<ul>
  <li>Test li 1</li>
  <li>Test li 2</li>
  <li>Test li 3</li>
  <li>Test li 4</li>
  <li>Test li 5</li>
</ul>

JS

Method 1

$('ul li').click(function(){alert('hi');});

Method 2

$('ul').children().click(function(){alert('hi');});

Method 1 and method 2 both works fine.

Which one is better ? Is it better to use the selector or use the children method ? What's the purpose of having a children method when we can use selector?

Test Fiddle

I'm just grabbing the basics and hope not knowing something is not a crime. Thanks

解决方案

While both of those pieces of code work correctly on the sample HTML they are not identical.

.children returns all child elements (whether they are an "li" or not).

"ul li" as a selector returns all "li" descendants of the "ul" whether they are children or not.

These two are equivalent and select only "li" children of the "ul" parent:

$('ul > li').click(function(){alert('hi');});
$('ul').children("li").click(function(){alert('hi');});

As for which is better (the original question), there is no real answer for this I suspect and will depend on your actual requirements and html (when you ask for which is 'better' what do you mean? Performance? Maintainability?).

Usually the former will use the CSS selector engine of the browser where the selector you are using is supported, and the later will always use jquery built code (I think) so I would go for the former in most cases.

这篇关于儿童vs选择器 - jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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