2012-11-29 48 views
0

我需要用img標記替換http://player.vimeo.com開頭的每個實例與另一個URL。用某些特徵替換HTML中的字符串

<img src="http://player.vimeo.com/video/4887233"> 

我試圖做一個jQuery的腳本,會發現每一個img SRC與http://player.vimeo.com開始,更換src與另一:

例如,您可能會在頁面的代碼中找到這字符串(它將是每個vimeo鏈接的相同字符串,基本上是一個變量)。

如何找到vimeo鏈接,並確保整個鏈接被替換不管長度(某些鏈接會比其他鏈接更長,但始終以相同的字符串開始)?

回答

4

選擇所有imgattribute starts with selector

$("img[src^='http://player.vimeo.com]'").each(function(){ 
    this.src = this.src.replace("player.vimeo.com", "new.url.com"); 
}); 

以上將src中的player.vimeo.com替換爲new.url.com。如果你需要設置另一個src,只需做this.src = 'new url';

值得一提的是,當你想改變原生屬性,如srceach將執行好得多相比attr,可在該jsPerf可以看出。

結賬demo on jsFiddle

+0

看起來不錯。有一種方法可以告訴腳本在頁面完全加載後啓動嗎? –

+0

當然,只需將它添加到[ready](http://api.jquery.com/ready/)事件回調中:'$(function(){/ *在這裏添加上面的代碼* /});' – mekwall

+0

@DannyCooper添加了演示基本用法的小提琴的鏈接。 – mekwall

1

你可以做的每個元素上的filter()並匹配src屬性,然後替換:

$('img').filter(function() { 
    return /^http:\/\/player\.vimeo\.com/.test(this.src); 
}).attr('src', 'somethingelse'); 

你也可以使用一個函數,而不是「somethingelse」如果你想要做個別更換,F。例如:

.attr('src', function(i, src) { 
    return src.replace(/vimeo/,'youtube'); 
}) 
2

http://api.jquery.com/attribute-starts-with-selector/

$("img[src^=\"http://player.vimeo.com\"]").attr("src", "new_string") 

$("img[src^=\"http://player.vimeo.com\"]").attr("src", function(i, val) {return val.replace("http://player.vimeo.com", "new url")}) 

沒有足夠的問題清楚,如果它應該有一些其他字符串替換整個鏈路或只是「http://player ...」,所以代碼兩種情況。

Markus Ekwall評論,attr爲大於每個慢,所以這將是更好的替代上面的代碼:

$("img[src^=\"http://player.vimeo.com\"]").each(function() {this.src = "new_string";}); 

$("img[src^=\"http://player.vimeo.com\"]").each(function() { this.src = this.src.replace("http://player.vimeo.com", "new url"); }) 
+0

+1如果你不需要做正則表達式匹配,這比濾波器更好。 – David

+1

'attr'與'each'相比非常慢(〜90%),可以在這裏看到:http://jsperf.com/attr-vs-each – mekwall

+0

@MarcusEkwall謝謝!真的很有趣的時刻,我不知道。 –

-1

使用這個,如果你只是想更換搜索URL。

$(function(){ 
    $('img').each(function(index,elem) { 
     var newValue = "http://youtube.com"; 

     var $this = $(this); 
     var strSrc = $this.attr('src'); 
     var regTest = /http:\/\/player\.vimeo\.com/; 

     if(regTest.test(strSrc)) { 
      $this.attr('src', strSrc.replace(regTest, newValue)); 
     } 
    }); 
}); 
0

訪問使用它的ID和更新後的HREF字符串URL傳遞給ATTR方法元素的href屬性:

<script> 
    $(document).ready(function(){ 
    $("button").click(function(){ 
    $("#link").attr("href","http://www.example.com/login.html"); //pass ur new url here 
    }); 
}); 
</script> 

的HTML體內:

<p><a href="http://www.example.com" id="link">Link name</a></p> 
相關問題