繁体   English   中英

Javascript-函数参数作为变量

[英]Javascript - Function Parameter As Variable

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

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

脚本位置: 此处

如果这是您的功能定义

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变量范围和使用全局变量(而不是传递参数)进行一些研究。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM