2016-06-27 62 views
-1

我已阅读关于同一主题的其他问题,并且我觉得我理解要做什么,但它不起作用。用jQuery替换href的一部分

我有两个域,出于必要性。在一个特定页面上,我试图更新链接,以便它们指向第二个域。它的功能,如果我只是循环每个'a'元素,但不是如果我尝试匹配特定的链接。我离开了我的第一次尝试评论,我不确定哪种方法更好。

如果某个页面位于特定页面上,但来自不同国家/地区,则会调用此函数。我看不到我做错了什么。

我认为this.href应该得到完整的,合格的URL,但它似乎并没有这样做。

function updateLinksToUSAstore() { 

    $('a[href*="manitobahdev.myshopify.com"]').each(function() { 
// $(this).attr('href', $(this).attr('href').replace('manitobahdev.myshopify.com', 'manitobahdev-us.myshopify.com')); 
     this.href = this.href.replace('manitobahdev', 'manitobahdev-us'); 
    }); 
    var CountryName = localStorage.getItem('CountryName');  
    // Change currently selected country text 
    $('#country-label, #country-label-mobile').text(CountryName); 
} 
+0

我看到不工作的唯一方法是,如果'$( 'A [HREF * = “manitobahdev.myshopify.com”]')'返回任何内容。你记录了返回的数组吗? –

+2

你能告诉我们一些'a'元素吗?我只是尝试了一个快速[jsfiddle](https://jsfiddle.net/kc6zLdpe/1/),它工作正常。确保在测试JavaScript时不使用缓存。 – Wikiti

+0

@Wikiti问题似乎是链接是相对的,但不应该this.href获取完整的URL? – Patrick

回答

0

试试这样说:

var href = null; 
$("a").each(function() 
{ 
    href = $(this).attr("href"); 
    if(href.contains("manitobahdev.myshopify.com")) 
    { 
    $(this).attr("href", href.replace("manitobahdev.myshopify.com", "manitobahdev-us.myshopify.com")); 
    } 
}); 

我在移动现在,所以我不能对此进行测试。很抱歉,如果它不起作用。 另外,我真的不明白你为什么会想只编辑manitobahdev部分manitobahdev美国,因为两端与myshopify.com

+0

在这种情况下,它们是两个不同的子域,因此它将链接到第二个商店。实际的实际URL是不同的。 – Patrick

0

也许它会帮助你。

//get all selector 
 
var celem=jQuery('a[href*="manitobahdev.myshopify.com"]'); 
 

 
for(var i=0;i<celem.length;i++){ 
 
    console.log('====== BEFORE ===='); 
 
    //get each href of selector 
 
var ele=jQuery(celem[i]).prop('href'); 
 
console.log(ele); 
 
    
 
    jQuery(celem[i]).prop('href',ele.replace('manitobahdev','manitobahdev-us')); 
 
    
 
console.log('====== AFTER ===');       
 
ele=jQuery(celem[i]).prop('href'); 
 
console.log(ele);        
 
          
 
          }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a id='test1' href="manitobahdev.myshopify.com/ABC">Test 1</a> 
 
<a id='test2' href="http://manitobahdev.myshopify.com/ZAXC">Test 2</a> 
 
<a id='test3' href="manitobahdev.myshopify.com/USER/1">Test 3</a>