Javascript - 函数参数作为变量

时间:2011-10-27 22:37:15

标签: javascript

我已经搜索了一下这个答案,所以这就是我想要做的 - 如果可能的话

function foo(variable){

如果我调用该函数,我该如何将该参数作为变量传递?

function foo(9){
    var stuff = 9;

//then pass variable to rest of script

以下是整个代码:

function ajaxgetter(variable) {
    var stuff = variable;
    var mygetrequest = new ajaxRequest();
    mygetrequest.onreadystatechange = function() {
        if (mygetrequest.readyState == 4){
            if (mygetrequest.status == 200 || window.location.href.indexOf("http") == -1){
                document.getElementById("result").innerHTML = mygetrequest.responseText;
            } else {
                alert("An error has occured making the request");
            }
        }
    }

    var namevalue = encodeURIComponent(document.getElementById("name9"+stuff).value);
    var agevalue = encodeURIComponent(document.getElementById("age9"+stuff).value);
    var utvalue = encodeURIComponent(document.getElementById("ut9"+stuff).value);
    document.getElementById("result").innerHTML = "<center><b>Loading...</b></center><br><center><img src='images/ajax-loader1.gif' /></center>";
    mygetrequest.open("GET", "newdealerfinder.php?location="+namevalue+"&distance="+agevalue+"&ut="+utvalue1"&r="+ Math.random(), true)mygetrequest.send(null);
}

Onclick事件(PHP):

$javacounter = 1;
if($miles1 > 2) {
                echo "<form action='' method='get' />
                <input type='hidden' value='$city->lat,$city->lng' id='name9$javacounter' name='name9$javacounter' />
                <input type='hidden' value='$currentunixtime' id='ut9$javacounter' name='ut9$javacounter' />
                <input type='hidden' value='$distance' id='age9$javacounter' name='age9$javacounter' />
                <input type='button' value='Coming Soon' onClick='ajaxgetter($javacounter)' />
                </form>";
                $javacounter++;
            }

脚本的位置: Here

2 个答案:

答案 0 :(得分:2)

如果这是你的功能定义

function foo(variable){
    var stuff = variable;
    alert(stuff);
    return stuff;
}

然后你调用它并传递一个像这样的值

var x = foo(9); //will alert 9
// use x..

// then pass variable to rest of script

不确定“脚本的其余部分”是什么。但是如果你想在函数外部访问它,你需要对Javascript变量范围和使用全局变量进行一些研究(而不是传递参数)。

您可以从函数中返回一个变量,以便在整个脚本中使用它。我更新了代码......

答案 1 :(得分:1)

我认为您正在尝试从函数调用中获取结果并在脚本的其余部分中使用它?

var foo = function (variable) {
    // do some stuff with variable
    return variable;
}

var result = foo(9);
// do whatever with result in rest of script