简体   繁体   English

如何在参数onload或dom准备就绪后调用函数?

[英]How to call a function with parameter onload or after dom is ready?

I have the following function that takes a selected value and runs it onclick. 我具有以下函数,该函数采用选定的值并在onclick上运行它。 I will still leave it that way. 我仍然会那样做。 However, client wants to have a default selected value which should run the function and this function makes changes on the page. 但是,客户端希望有一个默认的选定值,该值应该运行该功能,并且该功能会在页面上进行更改。

So how should I run this function by taking pre-selected value and run it after dom is ready without clicking anything? 那么,我应该如何通过获取预选值来运行此功能,并在dom准备就绪后不单击任何内容就运行它?

var value = $("#market-select option:selected").text(); // this takes value of pre-selected item
vizFilter1(value); // and I want to call this function after dom is ready or onload after passing values. 

I tried it this way but it is not doing anything. 我以这种方式尝试过,但是它什么也没做。

$(document).ready(function (){

function run (){
var value = $("#market-select option:selected").text();
vizFilter1(value);

}

}); 

How to run this after page has been loaded without requiring the user to do anything? 页面加载后如何运行而无需用户执行任何操作?

If you want to be able to run those two lines of code from multiple places, eg, from a click handler and on DOM ready, wrap them in a function (as you've done) and then call that function from your DOM ready handler. 如果您希望能够从多个位置(例如,单击处理程序和DOM准备就绪的地方)运行这两行代码,请将它们包装在一个函数中(已完成),然后从DOM准备就绪处理程序中调用该函数 Or simply bind the function as the ready handler: 或者简单地将函数绑定为ready处理程序:

function run (){
  var value = $("#market-select option:selected").text();
  vizFilter1(value);
}

$(document).ready(function (){
  run();
  // do other on ready things here if required
});

// OR, if you don't need to do other things:
$(document).ready(run);

In the attempt you showed, you declared a run() function but never called it. 在显示的尝试中,您声明了run()函数,但从未调用过它。 Though it is fine to define the function inside your ready handler as long as you then call it - that may be preferable as it keeps the function out of global scope. 尽管只要您随后在就绪的处理程序中定义函数就可以定义它,所以这可能是更好的选择,因为它可以使函数脱离全局范围。

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

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