开发者

A javascript Object ambiguous problem

开发者 https://www.devze.com 2023-01-18 00:10 出处:网络
this is a very very strange problem... see this code: <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">

this is a very very strange problem...

see this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>TEST</title>
<script src="http://misc.fandongxi.com/js/jquery.1.4.js" type="text/javascript"></script>
</head>
<body>

<a href="#" id="p1">click this to change p1.x</a>
<a href="#" id="p2">click this to change p2.x</a>

<input id="p1_val" value="">
<input id="p2_val" value="">

<script language="JavaScript">

a = function(id) {

    this.inputid = id+'_val';
    othis = this;
    $('#'+id).click(function(){
        othis.x += 1;
        $('#'+othis.inputid).val(othis.x);
    });

}


p1 = new a('p1');
p1.x=1;
p2 = new a('p2');
p2.x=1;

</script>


</body>
</html>

i wanna cli开发者_JAVA百科ck the ID "p1" to make p1.x add 1,and Click the "P2" to make p2.x add 1

but

the problem is click any of them...the p2.x will add 1

waiting for answer....

very thank you:)

i am not good at english....maybe i don't make the problem clearly;


I'm not really sure what you're overall goal is, but the error you're asking about is here:

othis = this;

It should be declared with var:

var othis = this;

Currently there's only one othis being shared, since it's a global variable when used without the var keyword before it.

You can see the updated/working version here.


You need to scope othis to the function. Currently it is used as a global variable.

var othis = this;
0

精彩评论

暂无评论...
验证码 换一张
取 消