Javascript将参数传递给函数 [英] Javascript passing parameters to function

查看:200
本文介绍了Javascript将参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

菜鸟问题:我有以下JavaScript函数。这工作正常但我不想硬编码字符串Names和namesDiv。我想将它们作为参数传递给getItems()。我该怎么做?

Rookie question: I have the following JavaScript functions. This works correctly but I don't want to hardcode the strings "Names" and "namesDiv". I want to pass them in as parameters to the getItems().How do I do this?

编辑:函数GetMsg()返回一个JSON对象:result。

The function GetMsg() returns a JSON object: result.

HTML:

<input type="button" onclick="getItems(); return false;" value="Go"/>

JS:

function getItems() {
   loadingMsg();
   GetMsg("Names", null, callback);
}

function callback(result, args){
   clearContainer();
   //do stuff
   document.getElementById("namesDiv").append(foo);
}

function loadingMsg(){
    clearContainer();
    // do stuff
    document.getElementById("namesDiv").append(foo);   
}

function clearContainer(){
    document.getElementById("namesDiv").innerHTML = "";
}


推荐答案

对于其中一半,它是明显;你刚开始将参数传递给函数:

For half of them, it's obvious; you just start passing the parameters to the function:

function loadingMsg(containerID) {
    clearContainer(containerID);
    document.getElementById(itemDiv).append(foo);   
}

function clearContainer(containerID) {
    document.getElementById(containerID).innerHTML = "";
}

回调是一个更复杂一点。我们将把它变成一个返回回调的函数。

callback is a little more complex. We'll turn it into a function returning the callback.

function makeCallback(containerID) {
    function callback(result, args) {
        clearContainer();
        document.getElementById(containerID).append(foo);
    }
    return callback;
}

现在我们可以调用 makeCallback 获得回调。我们现在可以写 getItems

Now we can call makeCallback to get a callback. We can now write getItems:

function getItems(itemType, containerID) {
   loadingMsg(containerID);
   GetMsg(itemType, null, makeCallback(containerID));
}

这篇关于Javascript将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆