a标签的href包含特定字符则用js替换url

a标签的href包含特定字符则用js替换url( 最好是用jquery的$(function()),其中a标签类名不一样,只是href中包含特定域名才替换为新的域名链接。例如:
原始代码中包含下面代码:

<a href="http://m.qq.com/1/2/aaa.html" class="aaaa">aaaaaa</a>
<a href="https://m.qq.com/3/4/bbb.html" class="bbb">bbbb</a>

只要检测到href中包含qq.com就替换href链接为设定好的统一新链接http://m.new.com。classs类中的参数保持不变。

阅读 7.5k
4 个回答
    <a href="http://m.qq.com/1/2/aaa.html" class="aaaa">m.qq.com</a>
    <a href="http://qq.com" class="aaaa">qq.com</a>
    <a href="qq.com" class="bbb">qq.com</a>
    <a href="https://m.qq.co" class="cccc">m.qq.co</a>
    <a href="https://aqq.com/3/4/ddd.html" class="ddd">aqq.com</a>
    <script>
        var hrefs = document.getElementsByTagName('a');
        var rexDomain = new RegExp('^.*?[\.|\/]qq\.com($|\/).*?$','i');//检测href属性中含有qq.com
        var newDomain = 'http://m.new.com';//用http://m.new.com替换
        for(var i=0,len=hrefs.length;i<len;i++){
            hrefs[i].href = hrefs[i].href.replace(rexDomain,newDomain)
        }
   </script>

//output

<a href="http://m.new.com" class="aaaa">m.qq.com</a>
<a href="http://m.new.com" class="aaaa">qq.com</a>
<a href="http://m.new.com" class="bbb">qq.com</a>
<a href="https://m.qq.co/" class="cccc">m.qq.co</a>
<a href="https://aqq.com/3/4/ddd.html" class="ddd">aqq.com</a>

document.getElementsByTagName(tagname)方法可返回带有指定标签名的对象的集合。
然后遍历集合并替换。

<a id="a1" href="http://m.qq.com/1/2/aaa.html">1111111111111</a>
<a id="a2" href="http://www.baidu.com/1/2/aaa.html">22222222222</a>
<script>
    var oA1 = document.getElementById('a1');
    var oA2 = document.getElementById('a2');
    
    var arr = [oA1, oA2];
    
    for(var a=0;a<arr.length;a++) {
        if(/m.qq.com/.test(arr[a].href)) {
            arr[a].href = 'http://m.new.com';
        }
    }
    
    // <a id="a1" href="http://m.new.com">1111111111111</a>
    // <a id="a2" href="http://www.baidu.com/1/2/aaa.html">22222222222</a>    
</script>

可以在点击的时候判断,用事件委托,我的代码求方便,直接在dcoment上添加了事件上,你可以选择你要的DOM,添加事件委托

document.addEventListener("click",function(e){
  if(e.target.tagName ==='A'){
    e.preventDefault()
    var href= e.target.getAttribute('href')
    if(/m.qq.com/.test(href)){
      location.href = 'https://www.sina.com.cn'
    } else {
      location.href = href
    }
  }

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题