在函数中输入10后,var变为NaN [英] var becomes NaN after incement by 10 in function

查看:64
本文介绍了在函数中输入10后,var变为NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var post = 10;
function load_more(str) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("add").innerHTML = document.getElementById("add").innerHTML + xmlhttp.responseText;
            }
        };
        var post = post + 10;
        xmlhttp.open("GET", "fetch_more.php?number=" + post , true);
        xmlhttp.send();
}

当我加载网站时,我希望浏览器定义值10来发布并且在我按下一个调用load_more()函数的按钮之前不做任何事情,该函数将该值递增10并通过Ajax将其传递给PHP。

When i load the website i expect the browser to define the value 10 to post and do nothing more until i press a button that calls the load_more() function which increments that value by 10 and passes it to the PHP via Ajax.

所需的行为是每次按下按钮时,在网站上发布10个帖子,然后在按下按钮上再加载10个。

The desired behaveiour is to have 10 post on the site and then load 10 more on button press each time the button is pressed.

但PHP只会抛出一个MySQL错误并且日志显示post var是NaN。

But PHP just throws an MySQL error and the log shows that the post var is NaN.

推荐答案

该行

var post = post + 10;

是罪魁祸首。 Javascript有一种名为 悬挂 ,这实际上意味着您的变量始终在范围的顶部声明。

is the culprit here. Javascript has a behaviour called hoisting, which essentially means that your variables are always declared at the top of the scope.

所以在您的代码中,会发生以下情况:

So in your code, what happens is the following:

var post = 10;
function load_more(str) {
    var post; // `post` is now undefined
    //...other code
    post = post + 10; // undefined + 10 evaluates to NaN
}

我希望你能看到,因为 post 在函数开头重新定义, post undefined 当您在 post + 10 中使用它时,会导致 post = post + 10 评估为 NaN (因为 undefined + 10 评估为 NaN )。

I hope you can see that since post is re-defined at the beginning of the function, post is undefined when you use it in post + 10, which causes post = post + 10 to evaluate to NaN (since undefined + 10 evaluates to NaN).

要解决您的问题,只需从前面删除 var

To solve your problem, just remove var from the front:

post = post + 10;

或:

post += 10;

这篇关于在函数中输入10后,var变为NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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