2013-08-24 226 views
1

我有這樣的代碼。當我在一個函數中使用硬編碼的jquery對象時,一切正常。但是當我想將它傳遞給一個函數調用時,我的函數不能識別jQuery對象,並且表沒有繪製。無法將jQuery對象傳遞給函數。如何安全地將jquery對象傳遞給函數?

// This is a function that draws a table. 
// I pass it the following params: 

     drawTbl({ 
      tbody: $("#tbl tbody"), // <tbody> element, jq object, This doesn't work. 
      tblElem: null, 
      tblTmpl: null, 
      tblContTmpl: "cont_tmpl", // id of a jQuery template 
      justAll: res.justAll, // some data for a table 
     }); 


// This is a function declaration 
// It doesn't draw a table if I pass tbody as a jquery object. 
// But works if I hard code tbody 
drawTbl = function(drawTblParams) { 

    drawTblParams.tbody.empty(); 


    // Loop to draw a table with jquery template 
    for (var m in drawTblParams.justAll) { 

     // This doesn't work, content isn't appended to tbody 
     $.tmpl(drawTblParams.tblContTmpl, { i: drawTblParams.justAll[m] }).appendTo(drawTblParams.tbody); 

     // This works fine, content is appended to tbody 
     $.tmpl(drawTblParams.tblContTmpl, { i: drawTblParams.justAll[m] }).appendTo($("#tbl tbody")); 
    } 

    // The most ridiculous thing 
    // This returns false! But it has to be the same element! 
    console.log(drawTblParams.tbody == $("#tbl tbody")); 

}; 

爲什麼jq對象失去其價值?如何將jquery對象傳遞給函數?

回答

1

如注意到here,您必須比較原始DOM元素(與jQuery包裝的元素相反)以確定相等性。這就是爲什麼你在控制檯中弄虛作假的原因。

我想你可以解決你的問題,如果你簡單地重新jQuery的IFY的方法中的對象,像這樣(?):的

$(drawTblParams.tbody).empty(); 

代替:

drawTblParams.tbody.empty(); 

等等貫穿你的方法。

0

我學到了什麼問題。我也動態地生成了一個<table>。在生成<table>之前,我會執行一個drawTbl函數調用。所以當我將jQuery <tbody>元素傳遞給函數調用時,DOM中沒有任何元素。

我解決了這個問題是這樣的:

drawTbl({ 
    tbody: "#tbl tbody", // I pass a string instead of a jQuery object 
    tblElem: null, 
    tblTmpl: null, 
    tblContTmpl: "cont_tmpl", // id of a jQuery template 
    justAll: res.justAll, // some data for a table 
}); 

而且在函數聲明我加了if

drawTbl = function(drawTblParams) { 

    // I generate a <table> before. So <tbody> is generated only now, not in the function call. 
    drawTblParams.tblElem.html($.tmpl(drawTblParams.tblTmpl)); 

    // Here I check if drawTblParams.tbody is a string and convert it to jq object 
    if(typeof drawTblParams.tbody == "string") 
     drawTblParams.tbody = $(drawTblParams.tbody); 

    // Now it exists 
    drawTblParams.tbody.empty(); 

    ... 

};