2013-08-24 171 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(); 

    ... 

};