2009-11-11 19 views
9

Digamos que hay un div que tiene contenido y un enlace de youtube. Quiero tomar ese enlace de youtube e incrustarlo.encuentra todos los enlaces de youtube con js (jquery)

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

Quiero tener el enlace y reemplazarlo por el código de inserción con js (jquery).

Actualización 1:

Ésta es mis js hasta ahora:

$("#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

La respuesta a esta pregunta podría ayudar con la parte de expresiones regulares: http://stackoverflow.com/questions/1713222/add -class-to-all-links-that-link-to-a-certain-domain-with-js-jquery – beggs

+0

BTW hay una API de JavaScript de YouTube que es razonablemente fácil de usar y bastante poderosa (listas de reproducción, etc.) https: // developers .google.com/youtube/js_api_reference –

Respuesta

15

¿Cambié el content de una identificación a una clase porque estaba adivinando que tendría más de un área de contenido?

Estoy seguro de que hay una forma mucho más eficiente de hacerlo, pero este es mi intento. Nota Me encantan las expresiones regulares, así que lo que tengo es lo más cerca que puedo, estoy seguro de que alguien puede ayudar a mejorarlo, por lo que no tiene que reemplazar el ?v= dentro de cada ciclo.

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> 

Guión

$(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) 
    }) 
    } 
}) 
}) 

seré el primero en admitir que no es bonito, pero funciona. También me pega una versión de trabajo de este código en this pastebin


Actualización: He limpiado el código un poco, aquí es cómo se ve ahora (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

Buena respuesta, solo cambio en mi respuesta debajo de – micmcg

+0

hola, también quiero eliminar el enlace de youtube y reemplazarlo por el video, ¿cómo puedo hacer eso? –

+0

@Waseem: actualicé la demostración (http://jsfiddle.net/9r7pj/20/), pero todavía me chupo en Regex. Agregué esta línea 'that.html (función (i, h) {return h.replace (/ (http: \/\/www.youtube.com \/watch \? V = \ w + ((\ & \ w + = \ w +) +)?)/g, '');}); 'y probé la expresión regular (http://rubular.com/r/QiOvgv8stR) y parecía funcionar allí, pero no en jsFiddle ... entonces no tengo idea. De cualquier manera, puede eliminar manualmente los parámetros adicionales de la url, si es necesario. – Mottie

1

que necesitará para obtener el contenido del div con algo como esto:

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

Con eso texto, puede usar la manipulación de cadenas o expresiones regulares para encontrar la url. A continuación, puede crear contenido jQuery para añadir con:

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

y añadirlo a algo con los métodos de manipulación de jQuery, como

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

Para obtener más detalles de los que, a su pregunta será necesario más detalles.

+0

He actualizado mi pregunta con mi js actual. Agregué comentarios a lo que necesito o a lo que me ato. – Amir

3

yo estaba en más o menos el mismo tema que el fudgey, pero me encantan las expresiones regulares incluso más que él, por lo que he "prestado" su código hasta ese momento. Un cambio que he hecho es usar swfobject para incrustar el video en lugar de manipular el código de inserción.Simplemente significa que hay que añadir la biblioteca swfobject a la página

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

HTML es el mismo que

<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> 

Pequeño cambio de fudgey al Javascript

$(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");      
       }) 
      } 
     }) 
    }) 

Felicitaciones a Tho respuesta de fudgey

+0

¡Agradable! Me olvidé de usar swfobject.js :) – Mottie

Cuestiones relacionadas