【问题标题】:Replace part of an href using jquery使用jquery替换部分href
【发布时间】:2014-01-06 21:59:10
【问题描述】:

我有一个加载页面的“iframe”。在此页面上,它有多个指向外部页面的链接,我想替换部分“href”,以便它链接到“Youtube”。例如,页面上的链接如下所示。

http://ytchannelembed.info/video.php?id=yQGAwrtB65A&t=

我想换

http://ytchannelembed.info/video.php?id=

有了这个

http://www.youtube.com/watch?v=

这样它最终会变成

http://www.youtube.com/watch?v=yQGAwrtB65A&t=

我尝试了一些 jquery 示例,但链接保持不变。如果有人可以提供帮助,我将不胜感激。

【问题讨论】:

  • 也许您可以发布您尝试过的内容。
  • 我试过$('a').each(function(){ this.href = this.href.replace('ytchannelembed.info/video.php?id=', 'www.youtube.com/watch?v='); });
  • @Sabre 所以它应该替换它。您在其他地方做错了什么,可能没有在正确的时间调用代码。你怎么称呼这段代码?
  • 我用过$(document).ready(function(){
  • @Sabre 所以请提供一个 jsfiddle 来复制您的问题(如果可以的话),因为您将在此处看到的所有答案都将与您已经使用的代码完全相同...

标签: javascript php jquery html youtube


【解决方案1】:

不用jQuery,试试这个:

var url = "http://ytchannelembed.info/video.php?id=yQGAwrtB65A&t=";
url = url.replace("http://ytchannelembed.info/video.php?id=","http://www.youtube.com/watch?v=")

【讨论】:

  • 感谢您的回答,但我有多个链接需要替换 http://ytchannelembed.info/video.php?id=
【解决方案2】:

这可以通过javascript和php来实现

PHP:

<?php
//Array with urls
$url = array("http://ytchannelembed.info/video.php?id=XXXXXXXX1","http://ytchannelembed.info/video.php?id=XXXXXXXXX2");
//Loop through urls
foreach($url as $u){
    //Dump new URLS to new array
    $new_url[] = str_replace("http://ytchannelembed.info/video.php? id=","http://www.youtube.com/watch?v=", $u);
}
//Dump all new URLS
var_dump($new_url)
?>

Javascript:

//Array with urls
var url = Array("http://ytchannelembed.info/video.php?id=XXXXXXXX1","http://ytchannelembed.info/video.php?id=XXXXXXXXX2");
//Declare new_url array
var new_url = Array();

//Loop through all urls
for(i=0; i<url.length; i++){
   //Push new URLS to new array
   new_url.push(url[i].replace("http://ytchannelembed.info/video.php? id=","http://www.youtube.com/watch?v="); 
}
//alert all new urls
alert(new_url);

【讨论】:

  • 感谢您的回答。如果您查看此jsfiddle.net/Hck4a,它应该有助于解释我的问题。
  • 我还是不明白你想要达到什么目的。
  • @PhilipG 他想修改跨域 iframe 的内容...通常从一开始就是一个不清楚的问题
  • 对不起,如果我没有说清楚,但我想自动将所有 http://ytchannelembed.info/video.php?id= 替换为 http://www.youtube.com/watch?v=,因为我无法更改每个特定链接,因为网页会定期接收新视频.
  • @Sabre 但是这些链接在跨域 iframe 中是否像在您的 jsfiddle 中一样???我希望你能更清楚地回答这个问题。答案应该是
猜你喜欢
  • 2017-02-26
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2011-04-28
  • 2015-08-31
  • 1970-01-01
  • 2013-01-05
相关资源
最近更新 更多