2009-11-11 3 views
9

콘텐츠 및 유튜브 링크가있는 div가 있다고 가정 해보십시오. 나는 그 유튜브 링크를 잡고 그것을 묻고 싶다.js (jquery)가있는 모든 유튜브 링크를 찾으십시오

<div id="content"><p>Here is a cool video. Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0</p></div> 

링크를 잡고 js (jquery)로 소스 코드로 바꾸기를 원합니다.

업데이트 1 :

var text = $("div#content p").html(); // or .text() 

그와 :

$("#content").each(function(){ 
    var allContent = $(this).html(); 
    //need regex to find all links with youtube in it, ovbiously it can't == youtube.com, but basically the link has to have youtube.com in it. 
    if ($("a",allContent).attr("href") == "youtube.com") { 
     // grab youtube video id 
     /* replace link with <div id="yt-video"> 
     <object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/429l13dS6kQ&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/429l13dS6kQ&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object> 
     </div> 
     */ 
    } 
}); 
+1

이 질문에 대한 답변은 정규식 부분에 도움이 될 수 있습니다. http://stackoverflow.com/questions/1713222/add js-jquery – beggs

+0

BTW에는 합리적으로 사용하기 쉽고 상당히 강력한 (재생 목록 등) https : // developers의 YouTube 자바 스크립트 API가 있습니다. .google.com/youtube/js_api_reference –

답변

15

content을 ID에서 클래스로 변경 한 이유는 하나 이상의 콘텐츠 영역이 있다고 생각했기 때문입니다.

나는 훨씬 더 효율적인 방법이 있다고 확신하지만, 이것에 대한 나의 시도이다. 참고 나는 정규식을 먹었으므로 내가 가지고있는 것만 큼 가까이 갈 수있다. 누군가가 그것을 향상시킬 수 있다고 확신하기 때문에 각 루프 안에 ?v=을 대신 할 필요가 없다.

HTML

<div class="content"><p>Here is a cool video. Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0 and this one http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div> 
<div class="content"><p>Here is a cool video. Check it out: http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div> 

스크립트

$(document).ready(function(){ 
// I added the video size here in case you wanted to modify it more easily 
var vidWidth = 425; 
var vidHeight = 344; 

$('.content:contains("youtube.com/watch")').each(function(){ 
    var that = $(this); 
    var txt = $(this).html(); 
    // Tthis could be done by creating an object, adding attributes & inserting parameters, but this is quicker 
    var e1 = '<obj'+'ect width="' + vidWidth + '" height="' + vidHeight + '"><param name="movie" value="http://www.youtube.com/v/'; 
    var e2 = '&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" ' + 
    'value="always"></param><em'+'bed src="http://www.youtube.com/v/'; 
    var e3 = '&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + vidWidth + 
    '" ' + 'height="' + vidHeight + '"></embed></object> '; 

    var vid = txt.match(/((\?v=)(\w[\w|-]*))/g); // end up with ?v=oHg5SJYRHA0 
    if (vid.length) { 
    $.each(vid, function(i){ 
    var ytid = this.replace(/\?v=/,'') // end up with oHg5SJYRHA0 
    that.append(e1 + ytid + e2 + ytid + e3) 
    }) 
    } 
}) 
}) 

나는 꽤 아니다 인정하는 최초의 수 있습니다,하지만 작동합니다. 또한 this pastebin


업데이트에서이 코드의 작업 버전을 붙여 : 나는 코드를 조금 청소했습니다, 여기가 (demo) 지금 모습입니다 :

$(document).ready(function(){ 
// I added the video size here in case you wanted to modify it more easily 
var vidWidth = 425; 
var vidHeight = 344; 

var obj = '<object width="' + vidWidth + '" height="' + vidHeight + '">' + 
    '<param name="movie" value="http://www.youtube.com/v/[vid]&hl=en&fs=1">' + 
    '</param><param name="allowFullScreen" value="true"></param><param ' + 
    'name="allowscriptaccess" value="always"></param><em' + 
    'bed src="http://www.youtube.com/v/[vid]&hl=en&fs=1" ' + 
    'type="application/x-shockwave-flash" allowscriptaccess="always" ' + 
    'allowfullscreen="true" width="' + vidWidth + '" ' + 'height="' + 
    vidHeight + '"></embed></object> '; 

$('.content:contains("youtube.com/watch")').each(function(){ 
    var that = $(this); 
    var vid = that.html().match(/(?:v=)([\w\-]+)/g); // end up with v=oHg5SJYRHA0 
    if (vid.length) { 
    $.each(vid, function(){ 
    that.append(obj.replace(/\[vid\]/g, this.replace('v=',''))); 
    }); 
    } 
}); 
}); 
+0

좋은 답변, 유일한 변경 내 대답은 – micmcg

+0

안녕하세요, 나는 또한 YouTube에서 링크를 제거하고 비디오로 교체하고 싶습니다, 어떻게 그럴 수 있습니까? –

+0

@Waseem : 데모 (http://jsfiddle.net/9r7pj/20/)를 업데이트했지만 정규식을 여전히 빨아들입니다. 나는이 줄을 추가했다.'that.html (function (i, h) {return h.replace (/ http : //www.youtube.com \ watch \? v = \ w + ((& (http://rubular.com/r/QiOvgv8stR)을 테스트했는데 거기에서 작동하는 것처럼 보였지만 jsFiddle에는 없었습니다 ... 그래서 나는 모른다. 어느 쪽이든 수동으로 URL에서 추가 매개 변수를 제거 할 수 있습니다. – Mottie

1

당신은이 같은 뭔가 사업부의 콘텐츠를해야합니다 :

이 지금까지 내 JS는 텍스트의 경우 문자열 조작이나 정규 표현식을 사용하여 URL을 찾을 수 있습니다. 그런 다음, 당신이 추가 JQuery와 콘텐츠를 만들 수 있습니다보다 자세한 정보를 얻으려면

var destination = $("body"); 
destination.append(content); 

처럼

var content = $('<a href="...">...</a>'); 

및 JQuery와의 조작 방법과 뭔가에 추가 질문이 필요합니다 자세한 내용은.

+0

내 질문을 현재 js로 업데이트했습니다. 내가 필요로하거나 내가 갇혀있는 것에 의견을 덧붙였다. – Amir

3

나는에 있었다 꽤 많은 fudgey와 같은 트랙이지만, 나는 그의 것보다 더 많은 regexps를 빨아들입니다. 그래서 나는 그 시점까지 그의 코드를 "빌려 왔습니다". 한 가지 변화는 swfobject를 사용하여 소스 코드를 핸드 롤링하는 대신 비디오를 포함시키는 것입니다.그냥

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js"></script> 

HTML이

$(function(){ 
    // I added the video size here in case you wanted to modify it more easily 
    var vidWidth = 425; 
    var vidHeight = 344; 

    $('.content:contains("youtube.com/watch")').each(function(i){ 
     var that = $(this); 
     var txt = $(this).html();  
     var vid = txt.match(/((\?v=)(\w[\w|-]*))/g); // end up with ?v=oHg5SJYRHA0 
      if (vid.length) { 
       $.each(vid, function(x){ 
        var ytid = this.replace(/\?v=/,'') // end up with oHg5SJYRHA0 
        var playerid = 'videoplayer_' + i + "_" + x; 
        that.append("<div id='" + playerid + "'></div>"); 
        swfobject.embedSWF("http://www.youtube.com/v/" + ytid, playerid, vidWidth, vidHeight, "8");      
       }) 
      } 
     }) 
    }) 

명예 Fudgey의 응답 상점에 자바 스크립트에 fudgey의

<div class="content"><p>Here is a cool video. Check it out: http://www.youtube.com/watch?v=oHg5SJYRHA0 and this one http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div> 
<div class="content"><p>Here is a cool video. Check it out: http://www.youtube.com/watch?v=fLBPsZVI8Gc&feature=player_embedded</p></div> 

작은 변화와 같은 당신이 페이지에 swfobject 라이브러리를 추가해야 의미

+0

니스! swfobject.js 사용을 잊어 버렸습니다 :) – Mottie

관련 문제