无法将jQuery对象传递给函数。如何安全地将jquery对象传递给函数?

时间:2013-08-24 19:13:32

标签: javascript 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-object失去了它的价值?如何将jquery对象传递给函数?

2 个答案:

答案 0 :(得分:1)

如前所述here,您必须比较原始DOM元素(而不是jQuery包装元素)以确定相等性。这就是你在控制台中弄错的原因。

我认为你可以修复你的问题,如果你只是重新jQuery-ify(?)方法内的对象如下:

$(drawTblParams.tbody).empty();

而不是:

drawTblParams.tbody.empty();

在整个方法中等等。

答案 1 :(得分:0)

我已经知道问题是什么了。我也动态生成<table>。在生成drawTbl之前,我会进行<table>函数调用。所以当我将jQuery <tbody>元素传递给函数调用时,DOM中没有任何<tbody>元素。

我用这种方式解决了问题:

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();

    ...

};