[英]Passing a variable into a JavaScript Function
我寫了一個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();
但是我想在調用函數時傳遞一個變量(電子郵件地址),但是我不確定該怎么做。 這個美元符號似乎妨礙了我! 任何想法表示贊賞。
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);
});
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]
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;
});
您只需通過傳遞值來調用函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.