简体   繁体   English

如何通过属性的 onclick 方法引用 javascript object?

[英]How can I reference a javascript object through a property's onclick method?

I am creating a Javascript object like so:我正在创建一个 Javascript object ,如下所示:

function pager(elementId) {
    this.totalPages = 5;
    this.currentPage = 1;

    var nextPageImage = document.createElement("img");
    nextPageImage.src = "img/next.png";

    nextPageImage.onclick = function(){
        if (this.currentPage+1 <= this.totalPages)
        {
            this.currentPage +=1;
        }
    }

    document.getElementById(elementId).appendChild(nextPageImage);
}

I create an instance of the object by passing in the id of a div on the page:我通过在页面上传入 div 的 id 创建了 object 的实例:

myPager = new pager('pagerDiv');

The problem is that the 'this' inside the onclick function refers to the image itself and not the pager object.问题是 onclick function 中的“this”指的是图像本身,而不是寻呼机 object。 I can reference the pager objct by using 'myPager' but that is not very practical.我可以使用“myPager”来引用寻呼机对象,但这不是很实用。

How can I reference the object from within the image onclick function?如何从图像 onclick function 中引用 object?

Create a local variable which represents "this" and then use that:创建一个代表“this”的局部变量,然后使用它:

function pager(elementId) {
    this.totalPages = 5;
    this.currentPage = 1;
    var th = this;

    var nextPageImage = document.createElement("img");
    nextPageImage.src = "img/next.png";

    nextPageImage.onclick = function(){
        if (th.currentPage+1 <= th.totalPages)
        {
            th.currentPage +=1;
        }
    }

    document.getElementById(elementId).appendChild(nextPageImage);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:如何通过方法调用定义对象的属性? - Javascript: How can I define an object's properties through method calls? 如何从javascript中返回的对象引用私有方法? - How can i reference a private method from returned object in javascript? 如何从 object 外部(通过事件)引用 javascript 中的 object 方法? - How do I reference an object method in javascript from outside the object (through event)? Javascript的object.onClick运行函数而不是设置onClick,如何防止这种情况发生,仅执行onClick函数? - Javascript's object.onClick runs the function instead of setting onClick, how can I prevent that from happening and only execute the function onClick? 如何在“this”方法中引用“this”属性? - How can I reference a `this` property within a method of `this`? 如何在javascript的构造函数中覆盖继承对象的属性? - How can I override an inherited object's property in the constructor in javascript? Javascript属性作为对其他对象属性的引用 - Javascript property as reference to other object's property Javascript:对象如何存储对另一个对象方法的引用,并“远程”调用它? - Javascript: How can an object store a reference to another object's method, and call it “remotely”? 如何在javascript中访问父对象的方法? - How can I access a parent object's method in javascript? JavaScript中对象属性的方法 - method for object's property in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM