简体   繁体   English

无法设法使JavaScript函数运行

[英]Can't manage to get JavaScript function running

I wrote the following function and put it between script tags in the header of my wordpress website. 我编写了以下函数,并将其放在wordpress网站标题中的脚本标签之间。

function turnShopBlue(){
    var location = window.location.href;
    if(location === "MY URL GOES HERE"){
        var menuItem = document.getElementById("menu-item-3352");
        menuItem.classList.add("current-menu-item");
        //document.querySelector("#menu-item-3352").addClass("current-menu-item");
    }
}
turnShopBlue();

But for some reason the function doesn't run. 但是由于某种原因该功能无法运行。 Each time I go the URL (page) that I choose in "MY URL GOES HERE", the class current-menu-item doesn't get added. 每次我进入“我的URL会在这里”中选择的URL(页面)时,都不会添加当前菜单项。 What do I miss? 我想念什么?

I've already tried with triple === and double ==, without success. 我已经尝试过使用Triple ===和double ==,但是没有成功。

EDIT SOLUTION: 编辑解决方案:

My mistake was that I placed the script in the header, the problem here is that the script then runs before the entire DOM is rendered. 我的错误是我将脚本放在标头中,这里的问题是脚本随后在呈现整个DOM之前运行。 So alot of the variables I instantiate don't have the good values. 因此,我实例化的很多变量都没有好的值。 The problem was solved by loading the script in the header; 通过将脚本加载到标题中可以解决此问题。

Also, I had to put it in a jQuery document ready function to autoload it on pageload. 另外,我必须将其放入jQuery文档就绪函数中,以在页面加载时自动加载。

Always put your Javascript code at the end (footer) of your body tag. 始终将Javascript代码放在body标签的末尾(页脚)。 This way, all your HTML will be parsed before any Javascript execution, further, your external scripts must be placed there as well to improve page's loading performance. 这样,您的所有HTML都将在执行任何Javascript之前进行解析,此外,您的外部脚本也必须放置在该处,以提高页面的加载性能。

<html>

<body>
  <tag-name id='menu-item-3352'></tag-name>

  <script>
    function turnShopBlue() {
      var location = window.location.href;
      if (location === "MY URL GOES HERE") {
        var menuItem = document.getElementById("menu-item-3352");
        menuItem.classList.add("current-menu-item");
        //document.querySelector("#menu-item-3352").addClass("current-menu-item");
      }
    }

    turnShopBlue();
  </script>

  <script external Javascript resources></script>
  <script external Javascript resources></script>
</body>

</html>

Resource 资源资源

$(document).ready equivalent without jQuery $(document).ready等同于没有jQuery

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

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