[英]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.