2017-09-02 39 views
0

我的网站的所有页面上都有一个NavMenu,它是一个包含图像的表格,用于引导您访问其产品页面。我正在尝试编写一个脚本,用于更改这些链接和图像下显示的名称,具体取决于正在查看网站的语言,但它不起作用。我已经改变了名称和链接作为示例,但基本上它是一回事。我使用Wordpress,并试图将脚本放在“header.php”中,并使用“Scripts n Styles”插件。另外,我对JavaScript也很陌生,所以不要阻止任何可能对我有用的批评。脚本不会根据当前的URL更改“href”和“div”内容

这是表,其中的产品的链接图片所在的HTML,我已经去除了大部分以方便您阅读:

<table style=width:100%> 
    <tbody> 
    <tr> 
     <td><a id="LinkToProduct" href=www.example.com/lt/product><img class="productIconImage" src="www.example.com/uploads/productimage.png/> 
     <div class="productIconName" id="ProductName">Product name in lithuanian</div> 
     </a> 
     </td> 
    </tr> 
    </tbody> 
</table> 

这是我写的剧本:

<script> 
     (function changeMainProductNavLinks() { 
      var currentUrl = location.href; 
      var parts = location.href.split("/"); 
      if (parts[1] == "eng") { 
      //Changing of the div text and href links. 
      document.getElementById("LinkToProduct").href = "www.example.com/eng/product"; 

      // Changing the url to english language site 
      document.getElementById("ProductName").innerHTML = "Product name in english"; 
     })() 
</script> 
+0

哪里是脚本位于何处?控制台中是否有错误?我的猜测部分[1]不是你想象的那样。 – epascarello

+0

你在HTML中包含脚本的地方? –

+0

没有任何错误出现在任何地方。目前我把它放在Header.php文件中的表格HTML之后。 – Augustas

回答

2
document.getElementById("").setAttribute("href", "http://...."); 

试试这种方法。

+0

会在一瞬间做。 – Augustas

+0

没有运气,仍然没有变化 – Augustas

+0

我试过我的代码,它与更改属性href一起工作..也许你给链接到你的函数有其他错误。 –

0

window.location.href包含http://所以parts[1]将是一个空字符串。

你可能想使用window.location.pathname或更改索引占http://

+0

其实我试图把数组改成零件[3],但也没有效果。将尝试与“window.location.pathname”虽然 – Augustas

+0

仍然无法正常工作 – Augustas

2

好吧,我终于想通了。问题是我没有放第二个“}”来结束函数,只有一个结束了“if”语句。这一直是问题,现在它运行良好。谢谢大家谁试图帮助

0

脚本改成这样

<script> 
     (function changeMainProductNavLinks() { 
      var currentUrl = location.href; 
      var parts = currentUrl.replace(/.*\//g,'').replace(/\?.*/g,''); 
      if (parts == "eng") { 
      //Changing of the div text and href links. 
      document.getElementById("LinkToProduct").href = "www.example.com/eng/product"; 

      // Changing the url to english language site 
      document.getElementById("ProductName").innerHTML = "Product name in english"; 
     }})() 
</script> 
相关问题