Jquery .click() 更胜一筹

发布于 2024-12-23 16:43:17 字数 268 浏览 3 评论 0原文

在我的类的方法中,我有:

this.background.click(function() {
    this.terminate();
});

显然 this.terminate(); 不起作用,因为 this 引用 this.background 内部 <代码>jquery.click函数。我该如何编写才能从上级获取 this

Inside a method of my class I have:

this.background.click(function() {
    this.terminate();
});

Obviously this.terminate(); doesn't work because this refers to this.background inside jquery.click function. How do I have to write for get this from superior class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

§对你不离不弃 2024-12-30 16:43:17

声明一个包含外部 this 的变量:

var self = this;
this.background.click(function() {
    self.terminate();
});

Declare a variable containing the outer this:

var self = this;
this.background.click(function() {
    self.terminate();
});
孤星 2024-12-30 16:43:17

尝试:

this.background.click( $.proxy( this.terminate, this ) );

Try:

this.background.click( $.proxy( this.terminate, this ) );
倾城°AllureLove 2024-12-30 16:43:17

你可以像@Andrew所说的那样,或者可以制作“yourObject.terminate();”

例如:

var yourObject = {
    background: $("#background"),
    terminate: function ()
    {
        alert("do something...");
    },
    addEvents: function ()
    {
        this.background.click(function()
        {
            yourObject.terminate();
        });
    }
};


$(function()
{
    yourObject.addEvents();
});

为了改进,请确保“background”选择器存在(如果 javascript 在 html 之前加载),并使用 jquery“live()”或“delegate()”或“on()”在元素中附加事件。

you can make like @Andrew said, or can make "yourObject.terminate();"

Ex:

var yourObject = {
    background: $("#background"),
    terminate: function ()
    {
        alert("do something...");
    },
    addEvents: function ()
    {
        this.background.click(function()
        {
            yourObject.terminate();
        });
    }
};


$(function()
{
    yourObject.addEvents();
});

for improve, ensure the 'background' selector exists (if javascript load before html), and use jquery "live()" or "delegate()" or "on()" to attach events in the elements.

森罗 2024-12-30 16:43:17

使用绑定

 $(".detailsbox").click(function(evt){
     test.bind($(this))();
  });
  function test()
  {
     var $this = $(this);
  }

Use bind

 $(".detailsbox").click(function(evt){
     test.bind($(this))();
  });
  function test()
  {
     var $this = $(this);
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文