Javascript 如何使函数在html页面中自动运行?

Javascript 如何使函数在html页面中自动运行?,javascript,jquery,html,Javascript,Jquery,Html,我正在使用JavaScript处理一个动态html页面,我想在不使用onclick的情况下自动运行一个函数,我想延迟执行它 我尝试了setTimeout(),但没有按预期工作 我如何将下面的代码转换为自动运行函数updateSliderValue(),并带有延迟但没有按钮 <!--creating a container for the input box--> <div><button onclick="updateSliderValue();">Set

我正在使用JavaScript处理一个动态html页面,我想在不使用
onclick
的情况下自动运行一个函数,我想延迟执行它

我尝试了
setTimeout()
,但没有按预期工作

我如何将下面的代码转换为自动运行
函数updateSliderValue()
,并带有延迟但没有按钮

<!--creating a container for the input box--> 
<div><button onclick="updateSliderValue();">Set value</button></div> 

设定值
代码是:

    }
         function updateSliderValue() {
            slider = widget.getByName("Slider1");
            slider.setValue();
        }

    </script>
</head>
<body>
<div style="clear: both; margin-top: 40px;"></div>
<div class="cell">
        <div class="container" style="height: 100px;">
            <div class="widget" style="height: 100%;" id="root">
            </div>
        </div>
    </div>
    <!--creating a container for the input box--> 
    <div><button onclick="updateSliderValue();">Set value</button></div> 


</body>
</html>
}
函数updateSliderValue(){
slider=widget.getByName(“Slider1”);
slider.setValue();
}
设定值

非常感谢您的努力和时间,但我不知道您给我的代码放在哪里。

要在页面加载时运行代码,您可以使用window.onload函数:

window.onload = function() {
  updateSliderFunction();
};
也可以使用$(文档)。准备好使用jquery解决方案:

$(document).ready(function(){
    updateSliderFunction();
});
当页面必须加载时,则在下方

$(function() {
    setTimeout(updateSliderValue,1000);
});

加载页面时它是否应该运行?“我尝试了setTimeout(),但它没有按预期工作。”-嗯,这就是要使用的工具。我们无法解释为什么您尝试使用它没有达到预期效果,因为(a)您没有向我们展示您的尝试,(b)您没有告诉我们您的行为与您预期的不同。@Quentin-预期效果是我对编辑的贡献之一。他只是说“setTimout不起作用”-虽然效果相同:)我更新了帖子,你能看一下吗?注意:第一个代码将在代码运行后立即开始超时。第二个将等待页面加载是的,只是想给他两个选项。他没有提到任何关于页面加载的内容,但是是的,我应该在我的回答中提到。非常感谢您的努力和时间,但我不知道您给我的代码放在哪里。就在代码中的updateSliderValue函数下面,您可以添加$(function(){setTimeout(updateSliderValue,1000);});我这样写,但没有结果:
}函数updateSliderValue(){slider=widget.getByName(“Slider1”);slider.setValue();}$(函数(){setTimeout(updateSliderValue,500);});设置值
$(function() {
    setTimeout(updateSliderValue,1000);
});