2016-06-13 111 views
2

我在如此多的頁面中設置了以下鏈接。如何使用jQuery查找和替換一些內容?

以下是其中有一些代碼.IE PHP文件:

輸入:

<a href="someurl/someotherfile.html"> Some Other file </a> 
    <a href="someurl/someotherfile1.html"> Some Other file1 </a> 
    <p><a href="someurl/someotherfile2.html"> Some Other file2 </a></p> 
    <div><a href="someurl/someotherfile2.html"> Some Other file2 </a></div> 
    <span><a href="someurl/someotherfile2.html"> Some Other file2 </a></span> 

輸出:

<a href="someurl/someotherfile.php"> Some Other file </a> 
    <a href="someurl/someotherfile1.php"> Some Other file1 </a> 
    <p><a href="someurl/someotherfile2.php"> Some Other file2 </a></p> 
    <div><a href="someurl/someotherfile2.php"> Some Other file2 </a></div> 
    <span><a href="someurl/someotherfile2.php"> Some Other file2 </a></span> 

現在,我想改變HTML到PHP擴展在HREF屬性。無需修改php代碼。

我試過下面的代碼,但它不起作用。注意到在這個代碼中發生。

$('a').each(function() { 
    $(this).html($(this).html().replace(".php", '.html')); 
}); 
+0

是什麼問題? –

+0

[Jquery在鏈接上更改擴展名]的可能的重複](http://stackoverflow.com/questions/37718477/jquery-change-extension-on-link-on-fly) –

回答

4

嘗試:

使用attr('href',value)設置新的href和使用.replace取代HTML到PHP

$(document).ready(function() { 
    $('a').each(function() { 
    $(this).attr('href',$(this).attr('href').replace(".html", '.php')); 
    }); 
}); 
+0

說明:因爲'.html()'是元素內部的文本,而不是它的href屬性。 –

0

.html()改變<a>標籤沒有內部href你所需要的內容裏面的內容改變href的值。

$('a').each(function() { 
 
    $(this).attr('href', $(this).attr('href').replace(".html", ".php")); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="someurl/someotherfile.html"> Some Other file </a> 
 
<a href="someurl/someotherfile1.html"> Some Other file1 </a> 
 
<p><a href="someurl/someotherfile2.html"> Some Other file2 </a> 
 
</p> 
 
<div><a href="someurl/someotherfile2.html"> Some Other file2 </a> 
 
</div> 
 
<span><a href="someurl/someotherfile2.html"> Some Other file2 </a></span>

0

你應該寫: -

$('a').each(function() { 
    var hrefVal = $(this).attr('href'); 
    $(this).prop("href", hrefVal.replace(".html", '.php')); 
}); 

檢查此鏈接prop vs attr

0

您可以更改網址,同時點擊鏈接。清除JS似乎更快

function replaceHref() { 
    this.href = this.href.replace('.html','.php'); 
    return true; 
}; 
window.onload = function() { 
    var arr = document.getElementsByTagName('a'); 
    for(i=0; i < arr.length; i++) 
      arr[i].onclick = replaceHref; 
};