最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Href and Store into Array jQuery - Stack Overflow

programmeradmin1浏览0评论

How do I get the first youtube video of each and store them into an array using jQuery?

HTML:

<div id="one">
    <ul class="thumbs">
        <li><a href=""></a></li>
        <li><a href=""></a></li>
    </ul>
</div>
<div id="two">
    <ul class="thumbs">
        <li><a href=""></a></li>
        <li><a href=""></a></li>
    </ul>
</div>

I think getting the link would be something like:

$('.thumbs li:first-child').attr("href");

But how do I get both of them and store them into an array?

How do I get the first youtube video of each and store them into an array using jQuery?

HTML:

<div id="one">
    <ul class="thumbs">
        <li><a href="http://www.youtube./watch?v=-dzpkn29_vY"></a></li>
        <li><a href="http://www.youtube./watch?v=xFCRMonf7lI"></a></li>
    </ul>
</div>
<div id="two">
    <ul class="thumbs">
        <li><a href="http://www.youtube./watch?v=UBTUAHGpQqE"></a></li>
        <li><a href="http://www.youtube./watch?v=mTkPfjSXFpo"></a></li>
    </ul>
</div>

I think getting the link would be something like:

$('.thumbs li:first-child').attr("href");

But how do I get both of them and store them into an array?

Share Improve this question asked Jan 17, 2012 at 23:46 user906080user906080 1252 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9
var arr = $('.thumbs > li:first-child > a').map(function() {
    return this.href;
}).toArray();
var arr = [];
$('#one, #two').find('.thumbs').each(function (index, element) {
    arr[arr.length] = $(this).find('a[href^="http://www.youtube./watch?v="]').eq(0).attr('href');
});

The bonus of using this type of search is that only elements with links to youtube are added to the array.

The arr array will now look like this:

["http://www.youtube./watch?v=-dzpkn29_vY", "http://www.youtube./watch?v=UBTUAHGpQqE"]

Note that beginning with the #one and #two elements is not necessary (you can start with .thumbs) however this limits the search to only those elements (in-case there are other .thumbs elements in the DOM).

Here is a demo: http://jsfiddle/fDQ2v/

发布评论

评论列表(0)

  1. 暂无评论