我改变了content
从一个 id 到一个类,因为我猜你会有多个内容区域?
我确信有一种更有效的方法可以做到这一点,但这是我的尝试。Note我对正则表达式很烂,所以我所拥有的是尽可能接近的,我确信有人可以帮助改进它,所以它不必取代?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>
Script
$(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 )
})
}
})
})
我会第一个承认它不漂亮,但它有效。我还将这段代码的工作版本粘贴到这个粘贴箱
更新:我已经清理了一些代码,现在看起来是这样的(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=','')) );
});
}
});
});