0

特定の要素のテキストを取得しようとすると、div複数のjQuery関数をチェーンするときに以前のすべての「一致」を取得するという非常に奇妙な動作があります。

これは私のコードです:

var rows = $("tr");
    var groups = [];
    for (var i = 0;i<rows.length;i++){
        if(rows.eq(i).html().toString().match(/TV/i)){
            groups += rows.eq(i).find(":first-child div").text();
        }
    }
    console.log(groups);

私が期待する出力は、一致したテーブル行の最初の子に含まれる div に含まれるテキストだけです。コンソールでその結果を取得しますが、その前に、すべてのテキスト、trすべての一致したtr( .eq(i))、すべての td の ( :first-childis a td)、すべてdivの および THEN 出力の最後のビットでテキストを取得します最初の に含まれていdivます。

だからgroups、私がこのようなことをしたように、すべてのものを保持しています:

groups += rows.eq(i)
groups += rows.eq(i).find(":first-child")
groups += rows.eq(i).find("div")
groups += rows.eq(i).find("div").text();

私は jQuery を初めて使用し、標準の JavaScript セレクターのみを使用しましgetElementById("myID").getElementsByTagName("div")[0].innerHTMLた。innerHTMLdivmyID

なぜこれが起こっているのですか、実際に探しているものをどのように入手できますか?

4

2 に答える 2

1

あなたのコードを調べた後、私はついにあなたの問題を見つけたと思います。DOM の出力が見えないので、わかりにくいです。

とにかく、を使用.find(':first-child div')すると、tr 内のすべての最初の子が取得されます。

例 :

td
-tr <-- Is :first-child (of td)
--div <-- is also :first-child and :first-child div (will get the text of this div)
---div <-- is also :first-child and :first-child div (will get the text of this div)
-tr
--div Is :first-child (of tr)
---div <-- is also :first-child and :first-child div (will get the text of this div)

代わりにこれを使用してみてください:

groups.push(rows.eq(i).children(":first-child").find('div').text());

それが役に立てば幸いです(そして実際にあなたの問題でした)!

于 2013-05-31T12:58:53.567 に答える