简体   繁体   English

如何使某个javascript函数在页面加载时对其所有元素执行?

[英]How do I make a certain javascript function execute on page load for all its elements?

I have a javascript function defined as follows (note that it does not use jquery): 我有一个定义如下的javascript函数(请注意,它不使用jquery):

function getCalculationFormsByType(selectObject, parentNode, countIndex)
{
    var operationID = parseInt(selectObject.value, 10);

    var divs = parentNode.getElementsByTagName("DIV");

    // the rest of the function goes here, it isn't really important ...
}

The function is executed in the following way (again, no jquery): 该函数以以下方式执行(再次,没有jquery):

<select name="operationChoose[]" onchange="getCalculationFormsByType(this, this.parentNode.parentNode, '1')" >

Everything works so far. 到目前为止一切正常。 The problem is that I need to execute this function on page load for all select elements on the page. 问题是我需要在页面加载时为页面上的所有select元素执行此功能。 Like this (my idea uses jquery, but it isn't necessary for the solution): 像这样(我的想法使用jquery,但对于解决方案而言不是必需的):

$("document").ready(function(){
   $("select[name='operationChoose[]']").each(function(){
      getCalculationFormsByType(---I DO NOT KNOW WHAT TO PASS HERE---);
   });
});

As you can see, my problem is that I don't know what to pass into the function in jQuery. 如您所见,我的问题是我不知道在jQuery中传递什么。 I don't know what those 3 values in javascript are and how can I get them in jQuery's each loop. 我不知道javascript中的这3个值是什么,如何在jQuery的each循环中获取它们。

The quotes in $("document").ready should be removed. $("document").ready的引号应删除。 Also, $(..function here..) is a shorthand for $(document).ready(...) . 同样, $(..function here..)$(document).ready(...)的简写。

This is the correct implementation: 这是正确的实现:

$(function() {
   $("select[name='operationChoose[]']").each(function(i) {  // <-- i-th element
      // this points to the <select> element, HTMLSelectElement
      getCalculationFormsByType(this, this.parentNode.parentNode, i);
   });
});

You need to be able to access javascipt's parentNode , so just transfer jQuery object to classic javascript one. 您需要能够访问javascipt的parentNode ,因此只需将jQuery对象转移到经典的javascript对象即可。

Additionaly, "document" will never work. 另外,“文档”将永远无法使用。 Use document or shorthand 使用document或速记

$(function(){
   $("select[name='operationChoose[]']").each(function(){
      getCalculationFormsByType(this, this.parentNode.parentNode, '1');
   });
});

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

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