为什么以下javascript中的用户地址“未定义”? [英] Why is the Address of the User “undefined” in the following javascript?

查看:44
本文介绍了为什么以下javascript中的用户地址“未定义”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <   html  >  
< head >
< script src = http ://code.jquery.com/jquery-1.10.1.min.js > < ; / script >
< script >
var user = {
名称:Doe,John,
位置:{
地址:123 Main Street,
city:New York,
state:NY,
zip:10001,
showAddress:function(){
alert('此用户的地址是:'+ this.location.address);
}
}
};
< / script >
< / head >
< body > ;
< div > 为什么上面的showAddress()函数中的警报说此用户的地址是:undefined?< / div >
< div > < 按钮 id = 运行 > 运行< / button > < / div >
< script >
$(function(){
$(#run)。click(user.location.showAddress);
});
< / script >
< / body >
< / html >

解决方案

(function(){


(#run )。click(user.location.showAddress);
});
< / script >
< / body >
< / html >


使用 this.address 而不是 this.location.address



showAddress 函数从位置。因此,指向位置 - 而不是用户。 ..


<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    var user = {
        name: "Doe, John",
        location: {
            address: "123 Main Street",
            city: "New York",
            state: "NY",
            zip: "10001",
            showAddress: function(){
                alert('The address of this user is: ' + this.location.address);
            }
        }
    };
</script>
</head>
<body>
<div>Why does the alert in the showAddress() function above say that "The address of this user is: undefined"?</div>
<div><button id="run" >Run</button></div>
<script>
    $(function(){
        $("#run").click(user.location.showAddress);
    });
</script>
</body>
</html>

解决方案

(function(){


("#run").click(user.location.showAddress); }); </script> </body> </html>


Use this.address instead of this.location.address.


The showAddress function is called from location. So, this points to location - not to user...


这篇关于为什么以下javascript中的用户地址“未定义”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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