dongzha2525 2016-07-02 02:07
浏览 17
已采纳

切换语言时留在当前页面的HTML代码

I'm writing this website which has a navigation bar on top of the window on which there's a toggle list that you can choose language you use to view this website.

I managed to wrote the code for the language switching button and here's the code:

<li class="dropdown ' . (in_array($currentFile,$servicesArr)?'active':'') . '">
<a class="dropdown-toggle">
    <img src="assets/images/flags/cn.png" width="16" height="11" alt="CN 語言" /> [CN] 简体中文<i class="fa fa-angle-down"></i>
</a>

<ul class="dropdown-menu">
     <li><a href="index.php">
          <img src="assets/images/flags/hk.png" width="16" height="11" alt="CN 語言" /> [HK] 繁體中文</a>
     </li>
     <li><a href="#">
         <img src="assets/images/flags/us.png" width="16" height="11" alt="EN Language" /> [US] English</a>
     </li>
 </ul>
</li>

So, my question is: according to my code, everytime I change a language, the link will take to the index of that language, but what if I'm not at the index page of my current language? Say, if I'm viewing index-en/job.php in English, now I want to switch to Chinese, instead of going to index-cn after click on the toggle button, I want to switch to index-cn/job.php. How can I do that?

Thanks in advance!

</div>
  • 写回答

1条回答 默认 最新

  • drebew5059 2016-07-02 03:09
    关注

    You used the php tag, so I'm guessing this is a PHP file. You can use PHP to dynamically populate the href attribute with the corresponding pages in the other languages.

    1. Get the current URL and language
    2. Compute what the matching URLs would be for the other languages.
    3. Insert matching URLs in the href attributes of your links.

    Code:

    <?php
    //URL path. eg: index-en/job.php
    $path = trim($_SERVER['REQUEST_URI'],'/');
    
    //language from URL. eg: index-en
    $lang = explode('/',$path)[0];
    
    //Paths in other languages: eg: 'cn' => 'index-cn/job.php'
    $langs = [
        'en'=>preg_replace("/$lang/",'index-en',$path,1),
        'cn'=>preg_replace("/$lang/",'index-cn',$path,1),
        ...
    ];
    ?>
    <ul class="dropdown-menu">
        <li><a href="<?= $langs['cn']?>">
                <img src="assets/images/flags/hk.png" width="16" 
                          height="11" alt="CN 語言" /> [HK] 繁體中文</a>
        </li>
        <li><a href="<?= $langs['en']?>">
                <img src="assets/images/flags/us.png" width="16" 
                          height="11" alt="EN Language" /> [US] English</a>
        </li>
    </ul>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题