每个元素的返回值

时间:2012-11-15 21:25:08

标签: jquery

我是jQuery的新手,我有一些麻烦让这件事有用。

<ul id="mediaGallery">
    <li><a href="#">https://www.youtube.com/watch?v=YVw7eJ0vGfM</a></li>
    <li><a href="#">https://www.youtube.com/watch?v=LW0k4eOEJ4U</a></li>
    <li><a href="#">https://www.youtube.com/watch?v=_SM7jtNOTXg</a></li>
</ul>

我们的想法是获取网址的最后一部分(例如: YVw7eJ0vGfM ),清空<a>元素并将其替换为<img>并返回最后一部分在图像的src路径末尾的网址,以便动态显示YouTube视频的缩略图。

//get the content of the <a> element
var video_href = $('#mediaGallery li a').html();

//get the last part of the url
var id_video = video_href.substr(video_href.length - 16);

//predifined img html whith the id of the video
var img_path = $('<img src="http://img.youtube.com/vi/'+id_video+'/0.jpg" />');

//empty the <a> element
$('#mediaGallery li a').empty();

//insert the img var
$('#mediaGallery li a').append(img_path);

问题是只返回第一个视频ID,并将其粘贴到所有<a>

我如何才能返回每个视频ID而不仅仅是第一个?

任何帮助都会受到很大的影响 感谢。

4 个答案:

答案 0 :(得分:2)

将其包装在$ .each:

$('li a','#mediaGallery').each(function() {
    var me = $(this),
        id = me.html().substr(video_href.length - 16);
    me.empty().append($('<img />').attr('src', 'http://img.youtube.com/vi/'+id+'/0.jpg')
});

答案 1 :(得分:1)

如果视频在ID后面有其他参数怎么办?我建议您使用each迭代的每个链接上的简单正则表达式提取id。

$('#mediaGallery li a').each( function() {
  var id = /\?v=(\w+)/.exec( $(this).text() )[1];
  ...
});

这应该可以帮助你走上正确的道路。

答案 2 :(得分:0)

你需要使用每个循环:

 $("#mediaGallery li a").each(function() {
    //get the content of the <a> element
        var video_href = $(this).html();

        //get the last part of the url
        var id_video = video_href.substr(video_href.length - 16);

        //predifined img html whith the id of the video
        var img_path = $('<img src="http://img.youtube.com/vi/'+id_video+'/0.jpg" />');

        //empty the <a> element
        $(this).empty();

        //insert the img var
        $(this).append(img_path);
    }

答案 3 :(得分:0)

使用$.each loop

$('#mediaGallery li a').each(function(){
    var video_href = $(this).html();
    var id_video = video_href.split("=")[1];

    var img_path = $('<img src="http://img.youtube.com/vi/'+id_video+'/0.jpg" />');

    $(this).empty().html(img_path);

});

<强> Check Fiddle