简体   繁体   English

在JS中调用函数不适用于参数

[英]Calling a function in JS doesn't work with arguments

In my JS file i'm calling one function from the other, at first i called it with no arguments by using only it's name handleResponse 在我的JS文件中,我要从另一个调用一个函数,起初我仅通过使用其名称handleResponse调用了不带参数的函数。
Then i tried adding arguments (of course by changing the function signature) and didn't get anything, so i tried calling the function as handleResponse() and even that didn't work. 然后,我尝试添加自变量(当然是通过更改函数签名),却一无所获,所以我尝试将函数称为handleResponse() ,即使这样也不起作用。
Why can't I call my function using brackets or using arguments ? 为什么不能使用方括号或参数调用函数?

Here are the functions : The main : 这里是功能:主要:

function sendRequest()
{
    var username = "";
    var game_id = -1;
    username = document.getElementById("username").value;
    game_id = document.getElementById("game_id").value;
    req.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id);
    req.onreadystatechange = handleResponse(username, game_id); <--- THIS IS THE CALL
    req.send(null);
}

Calling : (I changed the body, it's irrelevant). 呼叫:(我改变了身体,这无关紧要)。

function handleResponse(username, game_id) {
if(req.readyState == 4) {
    // DO SOMETHING...
    }
}

} }

You need to wrap that call in an anonymous function: 您需要将该调用包装在匿名函数中:

    req.onreadystatechange = function() {
      handleResponse(username, game_id); <--- THIS IS THE CALL
    };

The code you posted will call that handler at the point the assignment is made. 您发布的代码将在进行分配时调用该处理程序。 Instead of that, you need to assign a function that will be called when the ready state changes. 取而代之的是,您需要分配一个在就绪状态更改时将被调用的函数。

You are supposed to set a function reference to onreadystatechange and not execute the function. 您应该将函数引用设置为onreadystatechange ,而不执行该函数。 You can use closures to achive what you are trying to do. 您可以使用闭包来实现您要执行的操作。

req.onreadystatechange = function(){
    handleResponse(username, game_id);
}

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

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