开发者

What is the right way for JavaScript functions to accept variables

开发者 https://www.devze.com 2023-03-05 23:47 出处:网络
I\'m new to JS and a bit confused on this subject, I hope you\'ll understand the question: When I want to use in one function a variable coming from another,

I'm new to JS and a bit confused on this subject, I hope you'll understand the question:

When I want to use in one function a variable coming from another, or coming from an event such as onClick etc.. what would be the right way to move it from the HTML or another function into the executed function

working (well not yet..) example: i have a page with a few multi-choice questions, each question is a new form, i want to have one function for all the submit buttons, and when submitting to detect the name of the form, so should i use onsubmit="validate(this)? or is there a better way to take the form's name and put it to the validate function,

and also in general, when i use function something(){} and i want it to get variables from outside do i have to make function something(a,b,c){} or does it depends on the scope 开发者_开发百科of the variable? hmm.. i'm not even sure i understand enough to formulate a good question, so any reference to an article or tutorial on this topic will help a lot.


So there is a few core function concepts to JavaScript that should be able to help. First and formost: for dealing with DOM events you will probably want to rely on a library, unless you literally have 0 browser compatibility expectations. I suggest looking into jQUery.

That said, unobtrusive JavaScript (per @Raynos answer) is the right way to bind events in JavaScript and gives you a lot of flexibility. Take the following example:

function setup_events(){
  var my_form = document.form[0],
      form_name = my_form.name;
  my_form.addEventListener("submit", function(event) {
    console.log( form_name ); // this is retained through the closure.
  });
}

You see you can bind data into event functions by using the concept of a closure, or the context of an outer scope after the outer scope has returned from within an inner scope. Now when you execute setup_events you will bind the submit event with a function who internally has access to the outer variable form_name. This can produce some nasty side effects if you do not understand function scope so look out for code like this:

// XXX : BAD CODE
function setup_events(){
  var ul = document.getElementsByTagName('ul')[0], // assumes there is a <ul>
      count = 0;
  for ( var li in ul.childNodes ) {
    li.addEventListener('click', function( event ){
      alert( count ++ ); // this will always alert the count of list, not the list position
    }
  }
}

You can use Immediately Invoked Function Expressions to create the necessary closures to retain the correct state. So to "fix" the above code you would use something like:

// XXX : BETTER CODE
/**
 * NOTE: NEVER CREATE FUNCTIONS INSIDE A LOOP
 * this example only shows the immediate solution to the above problem
 * with regard to function scope and closures.
 */
function setup_events(){
  var ul = document.getElementsByTagName('ul')[0], // assumes there is a <ul>
      count = 0;
  for ( var li in ul.childNodes ) {
    li.addEventListener('click', (function( count ){
      return function ( event ){
        alert( count ); // this will alert the position in the list
      };
    })(count ++))
  }
}


I would recommend un obtrusive javascript.

document.form[0].addEventListener("submit", function(event) {
    switch (event.target.name) {
        // switch form name.
    }
});

When you design a general function you should think of the arguments you want to accept.

For example

function addNumbers(one, two) {
    // add them
}

Is designed to take two numbers. You should use your functions as they are designed with the correct arguments.

<div id="bar"> 3 </div>

...

(function() {
    // local variables
    var one = 1;
    var two = 2;

    // Your getting number 3 globally from the HTML.
    var three = document.getElementById("bar").textContent;

    // passed in as parameters
    console.log(addNumbers(one, two)); // 3
    console.log(addNumbers(two, three)); // 5

})();
console.log(one) // undefined.


Well if you have a function like:

function something(){
...
}

You can still do something like this:

something(1,2,3);

The results would be in an associative object in the function so you can access them like this:

function something(){
    //check for args:
    if(arguments === undefined){...}
    arguments[0]; //which is 1 in our case
    //etc
}

But in reference to an on{something}, you usually have to pass this, or use some sort of event handler


You could do something like this, not exactly, but you get the idea:

function onSubmitClick(){
    if(document.getElementById('choice1').checked==true){
        //store result
    }else if((document.getElementById('choice2').checked==true){
        //store result
    }else if(document.getElementById('choice3').checked==true){
        //store result
    }else if(document.getElementById('choice4').checked==true){
        //store result
    }else{
        //they didn't choose any
0

精彩评论

暂无评论...
验证码 换一张
取 消