簡體   English   中英

使用jQuery轉換頁面加載上的href鏈接

[英]Transforming href links on pageload using jquery

我需要將所有鏈接(href值)轉換為特定格式

例如-如果頁面具有鏈接http://www.exampledomain.com,我想將其href轉換為http://url.com/xyz?http://www.example.com

以下是我用於此任務的jquery(請注意,我是jquery新手)

$( document ).ready(function() {  
    $('a').each(function() {
        var value = $(this).attr('href');
        $(this).attr('href','http://url.com/xyz?'+value);
    });
});

但是上面的腳本正在轉換網站的所有鏈接,我的導航鏈接也正在更改。 我們如何過濾以僅更改包含“ http”和“ www”的鏈接的href?

我知道某種正則表達式可以用於此目的。 提前致謝!

我認為您應該提取所有內部鏈接。

您可以檢查值是否符合您的條件( http://www ):

   $( document ).ready(function() {  
     $('a').each(function() {
     var value = $(this).attr('href');
     if(value.indexOf("http:\\www") > -1 ){
         $(this).attr('href','http://url.com/xyz?'+value);
     }

   });

但是提取所有內部鏈接會更好:

var myHost = new RegExp(location.host);

$('a').each(function(){
   var value = $(this).attr('href');
   if(!(myHost.test(value))){
     $(this).attr('href','http://url.com/xyz?'+value);
   }
});

最后一個更好的選擇是僅采用外部鏈接:(如果您不必對內部進行任何操作)

 $( document ).ready(function() {  
    $("a[href^='http']").each(function() {
     var value = $(this).attr('href');
     $(this).attr('href','http://url.com/xyz?'+value);
    }

  });

您可以檢查鏈接是外部鏈接還是內部鏈接,然后可以添加額外的精力。

$( document ).ready(function() {  
 $('a').each(function() {
 var value = $(this).attr('href');
  if($(this[href^='http'])
  {
     $(this).attr('href','http://url.com/xyz?'+value);
   }
  });
});

您可以嘗試以下代碼

$( document ).ready(function() {   
    $('a').each(function() {
        var value = $(this).attr('href');
        if(value.match("http://www.*"))
        {
            $(this).attr('href','http://url.com/xyz?'+value);
        }
    });
});

您必須確保沒有導航鏈接包含

"http://www" 

在他們中。 在您不想替換href的地方使用相對鏈接。

或者,您可以為所有要進行相應修改的定位標記提供一個類

Demo Fiddle 使用元素檢查器檢查錨標記的href

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       var value = $(this).attr('href');
      $(this).attr('href','http://url.com/xyz?'+value);
   }
});  

使用window.location.hosttest

從CSS-Tricks.com上的本文修改

一種方法:

// selects all 'a' elements:
$('a')
// sets the 'href' attribute, using the anonymous function to iterate over each
// 'a' element:
.attr('href', function(i,oldhref){
    // i:  the index of the current element in the returned collection,
    // oldhref: the value of the 'href' before manipulation by the function.
    // if 'exampledomain.com' features in the hostname of the link we 
    // manipulate the 'href' as required, otherwise we simply set the 'href'
    // to its original value:
    return this.hostname.indexOf('exampledomain.com') > -1 ? 'www.url.com/xyz?' + oldhref : oldhref;
});

JS小提琴演示

參考文獻:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM