2012-05-08 101 views
0

我想更改鏈接的URL。如何使用Jquery更改鏈接的href?

下面的代碼

<div id="content"> 
    ... 
    <a href="/mbs/articleVC.php?mbsC=freebbs&mbsIdx=822907&cpage=10">link</a> 
    <a href="/mbs/articleVC.php?mbsC=freebbs&mbsIdx=822908&cpage=11">link</a> 
    <a href="/mbs/articleV.php?mbsC=freebbs&mbsIdx=802894&cpage=&mbsW=search&select=stt&opt=1&keyword=keyword1">link</a> 
    <a href="/mbs/articleV.php?mbsC=freebbs&mbsIdx=802895&cpage=&mbsW=search&select=stt&opt=1&keyword=keyword2">link</a> 
    ... 
</div> 

替換:

<div id="content"> 
    ... 
    <a href="/mbs/articleV.php?mbsC=freebbs&mbsIdx=822907&cpage=10">link</a> 
    <a href="/mbs/articleV.php?mbsC=freebbs&mbsIdx=822908&cpage=11">link</a> 
    <a href="/mbs/articleV.php?mbsC=freebbs&mbsIdx=802894&cpage=&mbsW=search&select=stt&opt=1&keyword=keyword">link</a> 
    <a href="/mbs/articleV.php?mbsC=freebbs&mbsIdx=802895&cpage=&mbsW=search&select=stt&opt=1&keyword=keyword2">link</a> 
    ... 
</div> 

有頁面上的許多鏈接。
如何用'article VC .php'替換爲'article V .php'使用jQuery?

+0

我很好奇, 「爲什麼?」你想要做到這一點。如果您已經永久移動或重命名頁面,則應更新HTML。否則,這應該使用'mod_rewrite'或'redirect 301'在服務器上完成。 – Sparky

+0

@ Sparky672我認爲這是一個好方法。但我不能。因爲這個問題是創建一個Chrome擴展。 – bbbig

+0

也許你可以提供一個關於這種瀏覽器擴展的真正目的的提示。 – Sparky

回答

1

第一個是更好,更快

$('#content a').attr('href', function(index, Oldhref) { 
    return Oldhref.replace(/articleVC/ ,'articleV') 
}); 

$('#content a').each(function() { 
    $(this).attr('href', $(this).attr('href').replace(/articleVC/ ,'articleV')); 
}); 
+0

感謝您的指導,感謝它 – bbbig

+0

@ user1382616歡迎,感謝的最佳方式是接受答案。 – thecodeparadox

+0

@thecodeparadox +1如果使用'this.href = this.href.replace(...)',第二個可以像第一個那樣快速高效。然而,如果效率是一個問題,for循環將是無論如何要走的路。 –

0

您可以使用:

$('#content a').each(function() { 
    $(this).attr('href', $(this).attr('href').replace('articleVC.php','articleV.php')); 
}); 

希望這有助於:)

0
$('a').each(function() { 
    $(this).attr('href', $(this).attr('href').replace('articleVC.php', 'articleV.php')); 
}); 

可以使用each功能遍歷所有匹配的<a>元素,爲他們每個人致電attr('href')走「href」屬性的屬性,使用的Stringreplace方法來獲取替換字符串,然後再爲它分配到'href'屬性。

1

你可以試試:

$('#content a[href*="articleVC.php"]').each(function() { 
    href = $(this).attr('href').replace('articleVC.php' ,'articleV.php'); 
    $(this).attr('href', href); 
});​​ 

Test Here

1
$('a', '#content').each(function() { 
    this.href = this.href.replace('articleVC', 'articleV'); 
});​ 

如果由於某種原因越快越好:-)

var elms = document.getElementsByTagName('a'); 
for (i=0; i<elms.length; i++) { 
    elms[i].href = elms[i].href.replace('articleVC', 'articleV'); 
} 
0

你可以做到這一點使用正則表達式。

使用jQuery:(jsfiddle

$('#content a').each(function() { 
    this.href = this.href.replace(/articleVC\.php/, 'articleV.php'); 
}); 

在香草的JavaScript:(jsfiddle

var links = document.getElementById('content').children; 
for(l in links) { 
    links[l].href = links[l].href.replace(/articleVC\.php/, 'articleV.php'); 
};