2016-06-13 115 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; 
};