简体   繁体   English

Javascript window.onload函数无法在新的链接文件上触发

[英]Javascript window.onload function not firing on new linked file

I have a dual language website and I wanted to toggle the href in the language link. 我有一个双语网站,我想切换语言链接中的href。 When visitors first visit the site, it loads the 'index.php' file. 访客首次访问该网站时,它将加载“ index.php”文件。 In the HEAD section of this file it calls a javascript file which has the following code: 在此文件的HEAD部分中,它调用一个具有以下代码的javascript文件:

window.onload = function() {

  var eng = document.getElementById("lang");
  var fn = location.pathname.substring(1)
  if (fn.match("En.php")) {
      eng.href = "index.php";
  } else {
      eng.href = "indexEn.php";
  }
}

The 'index.php' file it has an 'a' link element with a blank href (#) with an id of 'lang' which is the link to the English php file. 'index.php'文件包含一个'a'链接元素,其空白href(#)的ID为'lang',它是英语php文件的链接。 When I click that link it loads the IndexEn.php file just as the js code dictates. 当我单击该链接时,它将加载js代码指示的IndexEn.php文件。

The indexEn.php also has the call to the same javascript in the HEAD section and has the same 'a' link with the same id but the onload function doesnt run so it doesnt set the correct href. indexEn.php在HEAD部分中还具有对相同javascript的调用,并具有具有相同ID的相同“ a”链接,但onload函数未运行,因此未设置正确的href。 I have tested this with an alert in the onload function which doesnt display when indexEn.php loads. 我已经在onload函数中用一个警报测试了它,当indexEn.php加载时它不会显示。 I thought the onload function fired each time you called a file or have I misunderstood? 我以为每次调用文件时都会触发onload函数,或者我误解了吗?

Sounds like you really just need this to happen when the document is ready. 听起来好像您真的只需要在文档准备好时执行此操作即可。

Try this jQuery. 试试这个jQuery。

$(document).ready(function(){ 
    var eng = $("#lang");
    var fn = document.location.pathname.substring(1);
    if (fn.match("En.php")) { 
        eng.attr('href', "index.php"); 
    } else { 
        eng.attr('href', "indexEn.php");
    }
});

The non-jquery code. 非jQuery代码。 Put at the bottom of the page so that you can use the document selectors. 放在页面底部,以便您可以使用文档选择器。

    var eng = document.getElementById("lang");
    var fn = document.location.pathname.substring(1);
    if (fn.match("En.php")) { 
        eng.href = "index.php"; 
    } else { 
        eng.href = "indexEn.php";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM