2014-03-29 74 views
0

我有这个脚本在这里,我不知道如何传递这个变量来显示它。显示jQuery变量

function show(a) { 
    this.name = a; 
    $("#box").show(); 
    $(document).on("click","#box",function() { 
    alert(this.name); 
    }); 
    } 

我知道我可以只是提醒像这样

警报(一);

但在我的实际代码,我有一个动态可变SOI需要传递山雀和使用该方法显示它:

警报(this.name);

+2

因为'this'上下文不是那些2处一样的....我想你可以使用'性能表现( a){(“#box”)。show()。click(function(){ alert(a); }); }' –

回答

0

您可以使用bind

function show(a) { 
    this.name = a; 
    $("#box").show(); 
    $(document).on("click","#box",function() { 
     alert(this.name); 
    }.bind(this)); 
} 

bind返回一个函数,它绑定到特定的上下文。这样你有正确的上下文。当您更改上下文对象的属性name时,您的警报显示正确的name

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

也是一个很好的文章有关Function.prototype.bindhttp://coding.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/

+0

感谢您的帮助。 – user3446643

0

因为a是在封闭定义,你可以用a无处不在,而不是试图与this工作。