在动态生成的处理函数中访问javascript对象属性

时间:2012-05-18 16:10:28

标签: javascript jquery html

我有以下Javascript文件,其中一些html是动态生成的:

(function ($){

NunoEstradaViwer: {
  settings: {
  total: 0,
  format: "",
  num: 0;
  },
  init: function (el, options) {
  if (!el.length) { return false; }
    this.options = $.extend({}, this.settings, options);
    this.itemIndex =0;
    this.container = el;

    this.total = this.options.total;
    this.format = ".svg";
    this.num = 0;
    this.generateHtml(el);
  },
  generateHtml: function(container){
        var bnext = document.createElement('input');
        bnext.setAttribute("type", "button");
        bnext.setAttribute("id", "bnext");
        bnext.onclick = this.nextImage();
        bnext.setAttribute("value", "Next");
        container.appendChild(bnext);

  },
  nextImage: function(){
     this.num++;


 }
 });

我想要做的是访问NunoEstradaViwer函数中的num属性nextImage,而不是此对象指向bnext按钮。

你知道我怎么能管理它吗​​?

2 个答案:

答案 0 :(得分:1)

检查link

bnext.onclick = this.nextImage; // not bnext.onclick = this.nextImage();

另一件事是

NunoEstradaViwer.num++ ;  // instead of this.num++

答案 1 :(得分:1)

@rahen,我尝试了你的sugestions但不幸的是没有工作。 我发现对我有用的是一个包含jquery的解决方案。我做了以下事情:

generateHtml: function(container){
    var bnext = document.createElement('input');
    bnext.setAttribute("type", "button");
    bnext.setAttribute("id", "bnext");
    bnext.setAttribute("value", "Next");
    container.appendChild(bnext);

$("#bnext").bind('click',{viewer: this}, function(event) {
            event.data.viewer.nextImage();
        });

},
nextImage: function(){
 this.num++;
}

这样我可以访问num的值,并为NunoEstradaViwer更改。