1

私のページには、言語セレクタ オプションを含むドロップダウン メニューがあります。言語の選択時に、言語に応じてラベルとボタンの html を変更したいのですが? マイコード

var arr = [];
    //  gets all the ids starting with comp_
    $('div[id^="comp_"]').each(function(){
        arr.push(this.id);
        labels = $(this).find('label');
        buttons = $(this).find('button');

        //get all labels inside the current div
        $(labels,buttons).each(function(){
            $(this).html("");
        });

    });
    console.log(arr);
},

*問題 * ラベル要素の参照のみを変更し、ボタンの参照は変更しません。複数の要素の参照に対して関数を実行できますか?

これを行うと機能しますが、異なる参照に対して同じコードを繰り返したくありません

    var arr = [];
    //  gets all the ids starting with comp_
    $('div[id^="comp_"]').each(function(){
        arr.push(this.id);
        labels = $(this).find('label');
        buttons = $(this).find('button');

        //get all labels inside the current div
        $(labels).each(function(){
            $(this).html("");
        });

        $(buttons).each(function(){
            $(this).html("");
        });

    });
    console.log(arr);
},
4

1 に答える 1

2

はい:

    labels.add(buttons).each(function(){
        $(this).html("");
    });

あるいは単に:

    labels.add(buttons).html('');

1 文字短く:

    labels.add(buttons).empty();

.add()jQuery メソッドは、既存の jQuery コレクションに要素を追加するために使用されます。これらの例.add()では、「ラベル」および「ボタン」jQuery オブジェクトの要素を結合するために使用します。.each()2 番目の 2 つは、各要素に対して不変なことをしている場合は必要ないことを示すためのものです。ほとんどの jQuery 関数は、コレクションのすべての要素に対して本質的に動作します。

単純化するためのまったく異なる方法:

    var labelsAndButtons = $(this).find('label, button');
    labelsAndButtons.empty();

セレクター文字列の,は「または」のようなものです。この例では、タグ名が「label」または「button」であるすべての要素が検索されます。

于 2013-04-01T14:37:05.260 に答える