2

私は使用しており、選択内でオプションが変更されるたびjQuery 1.9.0にメソッドをトリガーしようとしています。on()それはうまくlive()いきましたが、おそらく私が見ていない単純なものだと思います。

これは私のHTMLです:

<select class="select_exercise">
    <option class="option_exercise">Example 1</option>
    <option class="option_exercise">Example 2</option>
</select>

と私のスクリプト:

$("option.option_exercise").on("change","option.option_exercise",function()
{
    alert("i am changing");
});

ここにフィドルがあります

4

6 に答える 6

6

この.on()メソッドを使用すると、イベント ハンドラーを DOM ツリーの上位に委譲できます。イベント ハンドラーを祖先要素にバインドしますが、そのハンドラーに到達したイベントがセレクターに一致する子孫要素で発生した場合にのみ、そのハンドラーを実行するという考え方です。

あなたの場合、それは次のようになります。

$(".select_exercise").on("change", ".option_exercise", function () {
// ^---- Probably no need to qualify the selectors with a tag name
    alert("i am changing");
});

ただし、サンプルコードを考えると、要素がイベントを発生optionさせることはないため、これは機能しません (ただし、要素は発生します)。要素が読み込まれた時点から DOM にあると仮定すると、要素に直接バインドできます。changeselectselect

$(".select_exercise").on("change", function () {
    alert("i am changing");
});

そして、それが最初に DOM にないbody場合は、より高く委任する必要があります (ここでは例として使用しています。読み込み時に DOM にある最も近い祖先に委任する必要があります)。

$("body").on("change", ".select_exercise", function () {
    alert("i am changing");
});
于 2013-01-31T11:16:27.103 に答える
1

$("option.option_exercise").on("change","option.option_exercise"する必要があります$("select.select_exercise").on("change",function()

デモ:フィドル

于 2013-01-31T11:15:14.593 に答える
1

次のことを試すことができます。

$(".select_exercise").change(function()
{
    alert("i am changing");
});
于 2013-01-31T11:16:39.957 に答える
0

あなたが使用することができます

$('.select_exercise').change(function() {
alert('Handler for .change() called.');
});
于 2013-01-31T11:17:29.340 に答える
0

Ok

オプションの1つではなく、select要素が変更されているかどうかを確認する必要があります。

この例では、「select_exercise」というクラスを持つselect要素が変更されているかどうかを確認しています。

そして、私はあなたが選択されたオプションを取得したいと思っているので、このコードを見てください

$(".select_exercise").on("change",function()
{
    alert($(this).find(":selected").text()); --Get the selected option text
    alert("i am changing");
});

フィドルの例

于 2013-01-31T11:17:45.790 に答える
0

これは正常に機能します。

$("select.select_exercise").on("change", function () {
    alert("i am changing");
});

選択は変更されるものであり、オプションではありません。変更されるのは選択の値であり、オプションではないためです。

于 2013-01-31T11:18:03.473 に答える