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

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

本文关键字:执行 元素 加载 何使某 javascript 函数      更新时间:2023-09-26

我有一个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 ...
}

该功能以以下方式执行(再次,无jquery):

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

到目前为止一切正常。问题是,我需要在页面上所有select元素的页面加载时执行此函数。像这样(我的想法使用jquery,但对于解决方案来说不是必需的):

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

正如您所看到的,我的问题是我不知道该向jQuery中的函数传递什么。我不知道javascript中的这3个值是什么,也不知道如何在jQuery的each循环中获得它们。

应该删除$("document").ready中的引号。此外,$(..function here..)$(document).ready(...)的简写。

这是正确的实现:

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

您需要能够访问javascipt的parentNode,所以只需将jQuery对象转移到经典的javascript对象即可。

此外,"文档"永远不会起作用。使用document或简写

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