将变量传递给JavaScript函数

时间:2017-06-17 23:50:56

标签: javascript jquery

我写了一个Javascript函数

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;
});

我将使用

打电话
newbie();

但是我想在调用函数时传入一个变量(电子邮件地址),但我不知道该怎么做。那个$符号似乎妨碍了我!任何想法都非常感激。

3 个答案:

答案 0 :(得分:1)

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;
}

 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);
  });

答案 1 :(得分:0)

javascript中的函数采用'参数'。您可以传入所需的参数,并在函数声明中定义其名称空间。即

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

有时你并不总是知道将要传入的内容或将会有多少个参数,在这种情况下,在函数声明中我们可以使用'arguments'对象来挑选传递给它的某些参数。功能

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

答案 2 :(得分:0)

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;

});

您只需通过传递值

来调用该函数