简体   繁体   English

jquery .children()of .get()

[英]jquery .children() of .get()

Example: 例:

<ul>
  <li>
    <a></a>
  </li>
  <li>
    <a></a>
  </li>
</ul>

I can use $('ul').children('li').get(0); 我可以使用$('ul').children('li').get(0); to get the list item. 获取列表项。 How can I use .children('a') to traverse down the tree? 我如何使用.children('a')遍历树?

I tried something like $('ul').children('li').get(0).children('a'); 我试过像$('ul').children('li').get(0).children('a'); but that does not work. 但这不起作用。


For future reference: 备查:

  1. I will be doing other things to the li other than traversing down to the a , which is why I am trying to use .children() . 除了遍历a ,我将对li做其他事情,这就是我尝试使用.children()
  2. Index will be dynamic and not always 0. 索引将是动态的,并不总是0。

Which is why .eq() is the preferred answer. 这就是为什么.eq()是首选答案。 Now I can do something like: 现在我可以这样做:

_load = function(index) {
  image_get = thumbs.children('li').eq(index);

  [...]

  $(function() {
    var img = $(new Image());
    img
      .load(function() {
        [...]
      }
      .attr('src', image_get.children('a').attr('href'));
  });
}

_load(0);

^^^ WIP. ^^^ WIP。 Code unfinished. 代码未完成。

.get() returns a DOM Element. .get()返回一个DOM元素。 You can wrap it back in a jQuery object like: 您可以将其包装回jQuery对象,如:

$($('ul').children('li').get(0)).children('a');

But I think what you really want is .eq() instead of .get() : 我认为你真正想要的是.eq()而不是.get()

$('ul').children('li').eq(0).children('a');

Edit 编辑

As Reid kindly pointed out in the comment below, 正如里德在下面的评论中指出的那样,

$('ul').children('li').eq(0).children('a');

is semantically equivalent to the more concise : 在语义上等同于更简洁:

$('ul > li:first-child > a');

which does the same as the above with a single selector. 使用单个选择器与上面的相同。

Why not just put it all in the selector and let that do all the work for you: 为什么不把它全部放在选择器中让它为你完成所有工作:

$('ul li:first a')

This will get a jQuery object for the first <a> tag in your sample HTML. 这将获得示例HTML中第一个<a>标记的jQuery对象。

The selector logic works like this: Find all ul tags, the find the first li tag in each, then get all the a tags in each of the first li tags. 选择器逻辑的工作方式如下:查找所有ul标签,找到每个标签中的第一个li标签,然后获取每个第一个li标签中的所有标签。 The result is a jQuery selection which you can then apply various operations to. 结果是jQuery选择,然后您可以应用各种操作。

Demo here: http://jsfiddle.net/jfriend00/5qZP5/ 演示: http//jsfiddle.net/jfriend00/5qZP5/

You can do this 你可以这样做

$('ul li a:first');

http://jsfiddle.net/jasongennaro/yCAT6/ http://jsfiddle.net/jasongennaro/yCAT6/

$('ul li a'); returns all of the a s in that list. 返回所有的a在那只名单。

:first filters for just the first. :first过滤器只是第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM