2010-04-26 45 views
1
function init_exam_chooser(id,mode) 
{ 
    this.id=id; 
    this.table=$("#" + this.id); 

    this.htmlRowOrder="<tr>" + $("#" + this.id + " tbody tr:eq(0)").html() + "</tr>"; 
    this.htmlRowNew="<tr>" + $("#" + this.id + " tbody tr:eq(1)").html() + "</tr>"; 
    $("#" + this.id + " tbody tr").remove(); 

    //Arxikopoiisi 
    var rowNew=$(this.htmlRowNew); 

    rowNew.find("input[type='text']").eq(0).autocomplete({ 
     source: function (req,resp) 
     { 

      $.ajax({ 
       url: "/medilab/prototypes/exams/searchQuick", 
       cache: false, 
       dataType: "json", 
       data:{codeName:req.term}, 
       success: function(data) { 
        resp(data); 
       } 
      }); 

     }, 
     focus: function(event,ui) 
     { 
      return false; 
     }, 
     minLength :2 

    }); 

    rowNew.find("input[type='text']").eq(1).autocomplete({ 
     source: function (req,resp) 
     { 

      $.ajax({ 
       url: "/medilab/prototypes/exams/searchQuick", 
       cache: false, 
       dataType: "json", 
       data:{name:req.term}, 
       success: function(data) { 
        resp(data); 
       } 
      }); 

     }, 
     focus: function(event,ui) 
     { 
      return false; 
     }, 

     minLength :2 
    }); 
    rowNew.find("input[type='text']").bind("autocompleteselect", function(event, ui) { 
     alert(htmlRowOrder); 
     var row=$(htmlRowOrder); 

     $(table).find("tbody tr:last").before(row); 
     alert(ui.item.id); 
}); 
    rowNew.appendTo($(this.table).find("tbody")); 


//this.htmlRowNew 

} 

問題是,我怎麼可以訪問htmlRowOrder? 我試了this.htmlRowOrder並沒有工作.... 任何想法??從函數的Javascript訪問對象變量

rowNew.find("input[type='text']").bind("autocompleteselect", function(event, ui) { 
      alert(htmlRowOrder); 
      var row=$(htmlRowOrder); 

      $(table).find("tbody tr:last").before(row); 
      alert(ui.item.id); 
    }); 

回答

4

你的問題是,this是不是你認爲這是你的事件處理程序中。大多數jQuery事件處理程序在觸發事件的元素的上下文中運行;這意味着在事件處理程序中,this是觸發事件的元素。

你可以通過等待JavaScript的下一個版本來解決這個問題,這個版本將會有一個Function.prototype.bind,或者通過設置一個對你的作用域對象的引用到事件處理器之外並引用它,帕特里克的答案。

function(){ 
    var instance = this; 
    this.foo = "abc123"; 
    $('someselector').click(function(ev){ 
     this.foo; //causes an error; foo is now the element matching 'someselector' 
     instance.foo; //this returns "abc123" 
    } 
} 
+0

你救了我的時間,謝謝 – GorillaApe 2010-04-27 00:05:18

1

您可以在函數外定義該變量。

var rowNew; 

function init_exam_chooser(id,mode) { 
    ... 
    rowNew=$(this.htmlRowNew); 
    ... 
} 

rowNew... 

當然,你將不得不調用函數rowNew之前將引用您要使用的值。


我用了一個不同的變量,但原理是一樣的。

或者,你可以讓你的函數返回你想要的值。

function init_exam_chooser(id,mode) { 
    // Do stuff 
    return myVariable; 
} 

var anotherVariable = init_exam_chooser(id,mode);