如何根据条件更改URL

时间:2014-07-29 04:28:06

标签: javascript wordpress

我需要根据window.location条件更改项目链接的URL。我对JAVA并不熟悉,所以对此有任何帮助或指导都会受到赞赏。感谢。

以下是我到目前为止用于手动更改所述项目内容的代码(它是针对单语WP主题制作的双语网站的解决方法......)

<ul class="block-with-icons clearfix">
    <li class="b1">
        <a href="http://test.ca/?page_id=69">
            <h5><script>
                if(window.location.href== "http://testfrench.ca/?lang=fr"){
                    document.write("Bonjour")
                } else {       
                    document.write("Hello")
                }
            </script></h5>
            <span> <script>
                if(window.location.href== "http://testfrench.ca/?lang=fr"){
                    document.write("Informez-vous")
                } else {       
                    document.write("Get informed")
                }
            </script>
            </span>
        </a>
    </li>

我现在需要的是链接路由到法语页面,而不仅仅是相同样式window.location条件下的英文页面。

3 个答案:

答案 0 :(得分:1)

 试试这个。我认为它运作正常

<li class="b1">

    <script>
         if(window.location.href== "http://testfrench.ca/?lang=fr"){
             document.write("<a href=\"french page\">");
            document.write("<h5>Bonjour</h5>");
            document.write("<span>Informez-vous</span></a>")
         } else {       
             document.write("<a href=\"http://test.ca/?page_id=69\">");
             document.write("<h5>Hello</h5>");
             document.write("<span>Get informed</span></a>")
         }
    </script>
 </li>

答案 1 :(得分:0)

应考虑使用javascript直接获取this等QS。话虽这么说,你要找的是:

if(window.location.href== "http://testfrench.ca/?lang=fr"){
    window.location.href ='http://yoursiteurlforfrench/pageurl';
}

window.location.href =将为您执行页面重定向,而if语句中的==正在对当前页面href与该字符串进行比较。

答案 2 :(得分:0)

将其添加到HTML的末尾:

<script>
    if (/[?&]lang=fr/.test(window.location.href)) {
        var anchors = document.getElementsByTagName('a');
        for (var i = 0; i < anchors.length; ++i) {
            var token = anchors[i].href.indexOf('?') == -1 ? '?' : '&';
            anchors[i].href = anchors[i].href.replace(
                /^(.*(?:[?&].*)?)(#.*)?$/,
                '$1' + token + 'lang=fr' + '$2'
            );
        }
    }
</script>

这将贯穿页面上的每个锚标签,并将lang = fr添加到href。

第一个条件包含正则表达式:

/[?&]lang=fr/.test(window.location.href)

这是一种更好的方式来说“法语页面”而不是:

window.location.href== "http://testfrench.ca/?lang=fr

...这迫使您在具有该确切网址的网页上使用此代码。

我建议你将它存储在页面顶部的布尔值中,如下所示:

<script>
    var isFrench = /[?&]lang=fr/.test(window.location.href);
</script>

然后你可以在你的条件下使用它:

if (isFrench) { /* ... */ }

getElementsByTagName获取页面上的所有锚标记,然后我们迭代每个标记,为每个标记更新href。

我们测试是否有“?”已经在URL中,在这种情况下我们想要使用“&amp;”改为附上lang param。

然后还有另一个非常简化的正则表达式来获取URL的第一个和最后一个部分,我们用中间的lang param替换整个href。