我在很多页面中设置了链接。 例如:
<ul>
<li> <a href="someurl/somefile.html"> Some file </a> </li>
<li> <a href="someurl/somefile1.html"> Some file1 </a></li>
<li> <a href="someurl/somefile2.html"> Some file2 </a></li>
</ul>
<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>
现在,我想将 html
更改为 php
扩展名。无需修改 php
代码。
我尝试了以下代码,但它不起作用。
$('a').each(function() {
$(this).html( $(this).html().replace( ".php", '.html' ) );
});
任何帮助将不胜感激。
最佳答案
您的代码中有两个问题:
1)您需要修改元素的属性href而不是html
2) 您已经交换了用 php 替换 html 的参数。第一个参数应该用于匹配,第二个参数用于替换。
$('a').attr('href',function(i,oldhref) {
return oldhref.replace( ".html",'.php');
});
工作片段:
$(function(){
$('a').attr('href',function(i,oldhref) {
return oldhref.replace( ".html",'.php');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> <a href="someurl/somefile.html" target="_blank"> Some file </a> </li>
<li> <a href="someurl/somefile1.html" target="_blank"> Some file1 </a></li>
<li> <a href="someurl/somefile2.html" target="_blank"> Some file2 </a></li>
</ul>
<a href="someurl/someotherfile.html" target="_blank"> Some Other file </a>
<a href="someurl/someotherfile1.html" target="_blank"> Some Other file1 </a>
关于Jquery 动态更改链接扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37718477/