[英]Why does jQuery select only one element when chaining .attr() in selector?
I have a simple list of links:我有一个简单的链接列表:
<ul>
<li><a href="1">link 1</a></li>
<li><a href="2">link 2</a></li>
<li><a href="3">link 3</a></li>
<li><a href="4">link 4</a></li>
<li><a href="5">link 5</a></li>
<li><a href="6">link 6</a></li>
<li><a href="7">link 7</a></li>
<li><a href="8">link 8</a></li>
<li><a href="9">link 9</a></li>
<li><a href="10">link 10</a></li>
</ul>
How do I select these links with jQuery?我如何 select 这些链接与 jQuery?
$('a')
- this returns all the links $('a')
- 这将返回所有链接
How do I get all the contents of these links ("link 1", "link 2", "link 3"...)?如何获取这些链接的所有内容(“链接 1”、“链接 2”、“链接 3”...)?
$('a').text()
How do I get all the hrefs from the links (1, 2, 3...)?如何从链接(1、2、3 ...)中获取所有href?
$('a').attr('href')
NOT TRUE ^ IT SELECTS ONLY THE FIRST LINK and returns 1
instead of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.不正确 ^ 它只选择第一个链接并返回1
而不是[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
。
I know I could map
, do each
etc. but I'm writing a crawler that uses this a lot and wondered why is this happening and whether I can get all the hrefs without any loops here, just using jQuery's (preferably jQuery core) selectors?我知道我可以map
,做each
等等,但是我正在编写一个经常使用它的爬虫,并想知道为什么会发生这种情况以及我是否可以在这里获得所有没有任何循环的href,只需使用jQuery的(最好是jQuery核心)选择器?
Demo: https://jsfiddle.net/z5j1ty08/演示: https://jsfiddle.net/z5j1ty08/
You can't really loop over DOM elements without, well, looping through them.如果没有循环遍历它们,您就无法真正循环遍历 DOM 元素。
Looping won't have any dramatic effect on the performance of your web-crawler.循环不会对您的网络爬虫的性能产生任何显着影响。
This being said, you're just looking at:话虽这么说,你只是在看:
$('a').each(function() {
console.log($(this).text());
});
Demo: https://jsfiddle.net/q1er5946/演示: https://jsfiddle.net/q1er5946/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.