jQuery在链接上动态更改扩展 [英] Jquery change extension on link on fly

查看:82
本文介绍了jQuery在链接上动态更改扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这么多页面中都设置了链接. 例如:

I have set of link in so many pages. Eg:

<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代码.

Now, I want to change html to php extension. without modifying the php code.

我尝试了以下代码,但是它不起作用.

I have tried following code but it does not work.

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

任何帮助将不胜感激.

推荐答案

您的代码中有两个问题:

You have two issues in your code:

1)您需要修改属性href而不是元素的html

1) You need to modify attribute href and not html of elements

2)您已交换了用php替换html的参数.第一个参数应为match,第二个参数应为替换.

2) You have swapped the arguments for replacing html with php. first argument should be for match and second one for its replacement.

$('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在链接上动态更改扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆