1

私はそのようなコードを持っています。関数でハードコードされた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オブジェクトを関数に安全に渡す方法は?

4

2 に答える 2

1

hereに記載されているように、生の DOM 要素 (jQuery でラップされた要素ではなく) を比較して同等性を判断する必要があります。そのため、コンソールで false になっています。

次のように、メソッド内のオブジェクトを単純に再 jQuery 化 (?) すると、問題を解決できると思います。

$(drawTblParams.tbody).empty();

それ以外の:

drawTblParams.tbody.empty();

など、メソッド全体で。

于 2013-08-24T19:23:19.067 に答える
0

何が問題だったのかを学びました。<table>私も動的に生成します。が生成されるdrawTbl前に関数呼び出しを行います。<table>したがって、jQuery 要素を関数呼び出しに渡す時点では、DOM には要素<tbody>がありません。<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();

    ...

};
于 2013-08-24T22:07:04.297 に答える