繁体   English   中英

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

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

我有一个定义如下的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');
   });
});

暂无
暂无

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

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