简体   繁体   中英

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):

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):

<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. Like this (my idea uses jquery, but it isn't necessary for the solution):

$("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. I don't know what those 3 values in javascript are and how can I get them in jQuery's each loop.

The quotes in $("document").ready should be removed. Also, $(..function here..) is a shorthand for $(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.

Additionaly, "document" will never work. Use document or shorthand

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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