2017-04-07 25 views
2

我添加了像這樣添加與jQuery的多個環節

$("a").filter(function() { 
       var ignoreLink = 
     this.hostname == location.hostname // disregard same domain 
     || this.href.match(/^(mailto|tel|javascript)\:/) 
       return !ignoreLink; 
      }).addClass("externalanchor").attr("target", "_blank"); 

上面的代碼工作正常過濾功能第三方鏈接的背景圖像需要的類別,現在我有一個要求,說一些鏈接應該是內部的ex:

<p><a href="https://www.google.com/" target="_blank">Email URL</a></p> 
<p><a href="https://github.com/" target="_blank">Google</a></p> 
<p><a href="https://www.w3schools.com" target="_blank">Google</a></p> 
<p><a href="https://www.codecademy.com" target="_blank">Google</a></p> 

我的問題是如何添加一個類爲這個鏈接單獨與一個dom只改變與jquery。

+0

你想添加一個類元件,其有目標空白?或者你想添加目標空白和一個類與外部網站的元素?我做了兩種方式,告訴我你想要什麼 – TriForce

+0

$(「a [href =」https://www.google.com/「], \t \t \t \t [href =」https://github.com/「], \t \t \t \t [HREF =」 https://www.w3schools.com 「], \t \t \t \t [HREF =」 https://www.codecademy.com 「]」).addClass( 「無外部」); \t});我需要像這樣的東西 – prad

+0

像'$('a [href^=「http」')。addClass('no-external')'? – Przemek

回答

1

您可以使用attribute contains selector

$("a[href*='google.com'], a[href*='w3schools.com'], a[href*='codeacademy.com']").addClass('no-external'); 
+0

yup working perfect thank you – prad

+0

@prad不客氣! –

+0

@susanth如果我在$(「a [href * =」w3schools.com「,a [href * =」codeacademy.com「],[href * =」google.com「)中使用雙引號, (jquery.min.js:4) ();}「)。addClass(」no-external「); Uncaught SyntaxError:missing) at Function.globalEval(jquery.min.js:2) at text script在Qb(jquery.min.js:4) at A(jquery.min.js:4) at XMLHttpRequest。 (jquery.min.js:4) – prad

0

也許這樣的事情對你的作品?:

https://jsfiddle.net/khkmmjjn/1/

代碼:

$("a").each(function(){ 

    if($(this).attr("href").indexOf("https://jsfiddle.net") == 0 || 
    $(this).attr("href").indexOf("jsfiddle.net") == 0) 
    { 
    $(this).addClass("local"); 
    } 
    else if($(this).attr("href").indexOf("mailto:") == 0 || 
    $(this).attr("href").indexOf("tel:") == 0) 
    { 
    $(this).addClass("other"); 
    } 
    else 
    { 
    $(this).addClass("external"); 
    } 

}); 
+0

yes有些東西在尋找感謝 – prad