如何根据条件更改URL

How to change a URL based on a condition

本文关键字:URL 条件 何根      更新时间:2023-09-26

我需要根据我的窗口更改一个项目链接的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>

我现在需要的是链接路由到法语页面,而不仅仅是在同一样式窗口上的英语页面。位置的状态。

try

试试这个。我想它可以工作

<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>

将此添加到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

…这将迫使您在具有相同URL的页面上使用此代码。

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

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

那么你可以简单地在你的条件下使用它:

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

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

我们测试URL中是否已经有"?",如果是,我们想用"&"来附加lang参数。

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

应该考虑使用javascript直接获取这样的QS。话虽如此,你要找的是:

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

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