简体   繁体   English

Javascript window.onload不触发

[英]Javascript window.onload not firing

I am trying to write a javascript function that forces an element to have the style display = block. 我正在尝试编写一个JavaScript函数,以强制元素具有样式display = block。 Currently it is being set to display = none by another piece of javascript. 目前,另一段javascript将其设置为显示=无。

I thought window.onload would solve the problem as the code is then not being overridden by the previous JS. 我认为window.onload将解决问题,因为代码不会被以前的JS覆盖。 The below code used to work and now the function just doesn't even fire. 下面的代码可以正常工作,现在该功能甚至无法启动。

Can anyone Help? 谁能帮忙?

          window.onload =  function ()   // It sets the class of the unordered list when the page has been loaded.
            {
               ul.style.display = "block!important";   // Display all the child items
             }

You need to get your ul in the callback of the event listener because if you do it before, the DOM is not fully loaded. 您需要在事件侦听器的回调中获取ul ,因为如果您之前这样做,则DOM不会完全加载。

document.addEventListener("DOMContentLoaded", function(event) { 
    var ul = document.getElementById("my-ul");

    ul.style.display = "block!important";
});

You can do it with JQuery if you want a more cross browser solution: 如果您想要更多的跨浏览器解决方案,则可以使用JQuery进行:

$(document).ready(function() {
    $('#my-ul').css('display', 'block!important');
});

You can do it in css: 您可以在CSS中执行此操作:

#my-ul {
    display: block!important;
}

Your ul should be of the form for these solutions to work: 您的ul应该采用以下形式的解决方案:

<ul id="my-ul">

You cannot use ul.style.display like that. 您不能像这样使用ul.style.display

Use document. getElementsByTagName('ul').style.display = "block !important" 使用document. getElementsByTagName('ul').style.display = "block !important" document. getElementsByTagName('ul').style.display = "block !important"

window.onload = function() ... is defining a function. window.onload = function()...正在定义一个函数。 Just call the function right after you close it with window.onload(); 使用window.onload()关闭函数后,只需调用该函数即可。 Worked for me after many hours 很多小时后为我工作

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

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