简体   繁体   中英

Passing a variable into a JavaScript Function

I have written a Javascript Function

jQuery(document).ready( function newbie($) {

    //var email = 'emailaddress'
    var data = {
        action: 'test_response',
        post_var: email
    };
    // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
    $.post(the_ajax_script.ajaxurl, data, function(response) {
        alert(response);
    });
    return false;
});

Which I will call using

newbie();

But I want to pass in a variable (the email address) when I call the function but I am not sure how to do this. That $ sign seems to get in my way! Any thoughts much appreciated.

jQuery(document).ready(function(){
   var email = 'emailaddress';
   newbie(email);
});


function newbie(email) {
    var data = {
        action: 'test_response',
        post_var: email
    };
    // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
    $.post(the_ajax_script.ajaxurl, data, function(response) {
        alert(response);
    });
    return false;
}

OR

 jQuery(document).ready(function(){
        var newbie = function(email) {
           var data = {
               action: 'test_response',
               post_var: email
           };
           // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
           $.post(the_ajax_script.ajaxurl, data, function(response) {
               alert(response);
           });
           return false;
      }

     var email = 'emailaddress';
     newbie(email);
  });

Functions in javascript take 'arguments'. You can pass in as many arguments you want and define their name space in the function declaration. ie

function foo(bar,baz,etc){
   console.log(bar,baz,etc);
}
foo(1,2,3)
 //logs out 1 2 3

Sometimes you don't always know what's going to be passed in or how many arguments there are going to be, in this case inside of the function declaration we can use the 'arguments' object to pick out certain arguments passed into the function.

function foo(){
   console.log(arguments);
}
foo(1,2,3)
 //logs out an array object that looks like this [1,2,3]

jQuery(document).ready( function newbie($, email) {

//var email = 'emailaddress'
var data = {
    action: 'test_response',
    post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
    alert(response);
});
return false;

});

you simply call the function by passing the values

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