2012-05-15 20 views
0

我有一個數組,其中包括一些網頁:從某些環節更換加長

var pages = ['test', 'blabla', 'xyz']; 

我的文檔中包含這樣的一些鏈接:

<a href="test.php">tes</a> 
<a href="blabla.php">blabla</a> 
<a href="xyz.php">xyz</a> 
<a href="stackoverflow.php">test2</a> 

什麼,我想是這樣的:

我要搜索整個文檔,發現各個環節,即開始在我的陣列的話。然後,我要替換「.PHP」與名「.html」和前面加上當前的URL(不含文件)對他們說:

location.href.substring(0,location.href.lastIndexOf('/')+1) 

所以,預期的結果應該是這樣的:

<a href="file:///C:/test.html">test</a> 
<a href="file:///C:/blabla.html">blabla</a> 
<a href="file:///C:/xyz.html">xyz</a> 
<a href="stackoverflow.php">xyz</a> 

我的嘗試是這樣的:

$(function(){ 
var pages = ['test', 'blabla', 'xyz']; 
$.each(pages, function(index, value) { 
$("a[href='" + value + ".php']").attr("href", location.href.substring(0,location.href.lastIndexOf('/')+1) + $("a[href='" + value + ".php']").attr("href").replace('php', 'html')); 
}); 
}); 

這工作,但並非總是如此。我一個更大的文檔在嘗試這樣做,它有這個錯誤結束:

$("a[href='" + value + ".php']").attr("href") is undefined

我想,還有更簡單,更好,更兼容的方式。但我不知道,這就是爲什麼我在這裏問:d

回答

0
var pages = ['test', 'blabla', 'xyz']; 
$.each(pages, function (index, value) { 
    $('a[href$=' + value + '.php]').attr("href", function() { 
     return ('file:///C:/' + $(this).attr('href').replace('.php', '.html')); 
    }); 
}); 
+0

與小改工作。我不得不改變$( 'A [HREF $ =' +價值+」 .PHP] '),以$( 「一[HREF $ ='」 +價值+」 .PHP「]」) 謝謝:) – user1395597

0
var pages = ['test', 'blabla', 'xyz']; 
$('a[href$=".php"]').each(function() { 
    var hrefWithoutext = this.href.replace('.php',''); 
    if($.inArray(hrefWithoutext, pages)){ 
    this.href = 'file:///C:/' + hrefWithoutext + '.html'; 
    } 
});​