[英]jquery get a href using attr() doesn't work
I have a page* with several .article
divs with the following markup: 我有一个页面*包含几个带有以下标记的
.article
div:
<div class="article">
<div class="featured-img">
<a href="https://www.johornow.com/english/things-to-do-at-kota-tinggi/" style="background: none;">
</a>
</div>
<div class="featured-info">
<h3 class="article-title">
<a href="https://www.johornow.com/english/things-to-do-at-kota-tinggi/">Fun Things to Do and Amazing Places to Visit at Kota Tinggi</a>
</h3>
</div>
</div>
Now I want to get all the anchor links: 现在,我想获取所有锚点链接:
$('.article').each( e => $(this).find('article-title').find('a').attr("href") )
Surprisingly I failed to do so, I got DOM node. 出乎意料的是,我没有这样做,我得到了DOM节点。 What's wrong with my code?!
我的代码有什么问题?
* https://www.johornow.com/english/travel/ * https://www.johornow.com/cn/travel/
There are couple of errors in your code: 您的代码中有几个错误:
1) JQuery is all about chaining, that's why functions like each
return the initial set and not the elements you return in the function (or a collection of your return values?). 1)JQuery与链接有关,这就是为什么
each
类似的函数each
返回初始集合,而不返回您在函数中返回的元素(或返回值的集合?)的原因。 What you want/need here is .map
. 您想要/需要的是
.map
。
2) your find was missing the .
2)您的发现缺少
.
for addressing a class. 用于上课。 Also, you can write it in a single statement
find(".article-title a")
. 另外,您可以在单个语句
find(".article-title a")
编写它。
3) Fat arrow functions don't establish their own context, thus $(this)
won't work. 3)粗箭头功能无法建立自己的上下文,因此
$(this)
不起作用。 Instead you have to use the "old-school" way of writing functions, to actually have this
refer to the single elements. 取而代之的是,您必须使用“古老的”编写函数的方法,才能使
this
函数实际上引用单个元素。
The following jquery solution 以下jQuery解决方案
$('.article .article-title a').map( function(){return console.log($(this).attr("href"))} )
creates an array with all the link hrefs. 创建一个包含所有链接hrefs的数组。
So does the following vanilla JS (which I actually always prefer): 以下香草JS(我实际上总是很喜欢)也是如此:
[].map.call(document.querySelectorAll('.article .article-title a'), e=>e.href )
There you have your fancy fat arrow again - also, it's shorter, (possibly faster) and does not rely on third-party;) 在那里,您又有了花哨的粗箭头-而且,它的箭头更短(可能更快)并且不依赖第三方;)
You can get all the links in an array 您可以获取数组中的所有链接
var m =[];
$('.article').each(function(e,v){
m.push($(this).find('h3 > a').attr("href"))
})
console.log(m)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.