我不想运行一个函数,只是将它用作参数,但它会不断弹出

时间:2012-11-06 11:51:49

标签: javascript function parameters

我已经在其他答案中读到,为了将函数用作参数,需要将其编写为whatever;而不是whatever(),因为此las选项“调用”该函数。但是,如果我需要指定所述函数的参数呢?我举个例子:

我有这个功能来替换一些内容:

function navigate(content) {
var card = document.getElementById('informationdiv');
card.innerHTML = content;
} 

然后我有另一个创建内容的函数:

function productsheet(article) {
    document.write(array_products[article].Name);
    document.write(array_products[article].Number);
    document.write(array_products[article].Type);
    // and so on...

然后,我想调用第一个函数:

navigate(productsheet(article));

而不是替换innerHTML,它只运行productsheet(article)覆盖其他所有内容。

正如我所说的,我发现类似的问题,解决方案是在没有productsheet的情况下通过(article),但在我的情况下,我需要article参数,因此productsheet知道要打印的内容。 ..

这里建议的方法是什么?

非常感谢!

2 个答案:

答案 0 :(得分:3)

如果我已正确理解您的问题,您需要将匿名函数传递给navigate并在其中调用您的productsheet函数:

navigate(function () {
    productsheet(article);
});

但是,我不确定你想要实现什么......你可能想要摆脱那些document.write调用并从productsheet返回一个字符串,然后调用该函数而不是将引用分配给innerHTML

card.innerHTML = content();

答案 1 :(得分:0)

有更好的方法可以达到你想要的效果,但是以你的代码作为出发点我会做如下:

navigate(article);

function navigate(article) {
    var card = document.getElementById('informationdiv');
    card.innerHTML = productsheet(article);
}

function productsheet(article) {
    //here you would return a string that has the format as how you would like to display it
    return "... name, number, type ...";
}

同样,我认为你应该重新考虑整个方法并抛弃这些代码。