[英]JS: How to add more than one URL into a Javascript-Code?
我在我的wordpress functions.php文件中使用以下代碼,將nofollow自動添加到特定網址的每個鏈接中:
function cdx_handel_external_links() {
?>
<script type="text/javascript">
( function( $ ) {
$("a[href^=http]").click(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank"
});
}
})
//Add Nofollow
$("a").each(function(){
if(this.href.indexOf('example-url.com') >0 ){
$(this).attr({
rel: "nofollow"
});
}
});
} )( jQuery );
</script>
<?php
}
add_filter( 'wp_footer', 'cdx_handel_external_links', 999);
但是,如何在該代碼中添加新的URL? (我是編碼新手,很抱歉)。 也許通過: indexOf('example-url.com','example-url2.com','example-url3.com')
嗎? 非常感謝您的幫助!
編輯:
作為完全菜鳥,我通過以下方式進行操作,它對我有用:
function cdx_handel_external_links() {
?>
<script type="text/javascript">
( function( $ ) {
$("a[href^=http]").click(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: "_blank"
});
}
})
//Add Nofollow
$("a").each(function(){
if(this.href.indexOf('example-url.com') >0 ){
$(this).attr({
rel: "nofollow"
});
}
});
//Add Nofollow 2.domain
$("a").each(function(){
if(this.href.indexOf('example-url2.com') >0 ){
$(this).attr({
rel: "nofollow"
});
}
});
//Add Nofollow 3.domain
$("a").each(function(){
if(this.href.indexOf('example-url3.com') >0 ){
$(this).attr({
rel: "nofollow"
});
}
});
} )( jQuery );
</script>
<?php
}
add_filter( 'wp_footer', 'cdx_handel_external_links', 999);
您可以使用Array.prototype.includes() :
const urls = ['www.example-url.com', 'www.example-url-1.com', 'www.example-url-2.com']; $('a').each(function() { if ( urls.filter(url => url.includes('example-url.com')).length > 0 ) { $(this).attr({ rel: 'nofollow', }); } });
我們想知道href字符串是否包含一組禁止的子字符串之一。
let nonFollow = ['example-url.com','example-url2.com','example-url3.com'];
function isNonFollow(anHref) {
for (i=0; i < nonFollow.length; i++) {
let href = nonFollow[i];
if (anHref.indexOf(href) >0) return true;
});
return false;
}
$("a").each(function(){
if(isNonFollow(this.href)){
$(this).attr({
rel: "nofollow"
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.