1

このコード行を機能させようとしています。

$(".selectnumber").text($(this).parent().find('select').children(':selected').text());

選択のテキスト値を取得して、選択番号スパンに入れたいだけです。

alert($(".selectnumber").parent().find('select').children(':selected').text()); 

正常に動作し、正しい値を返すので、期待どおりに $(this) が .selectnumber スパンを参照していないと仮定する必要があります。

何かに影響を与える場合に備えて、HTMLもここに示しますが、影響はないと思います。

<div class="holder">
    <span class="selectnumber"></span>
    <select id="number_of_cards_required" name="number_of_cards_required">
        <option selected="selected">1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
</select>
</div>
4

5 に答える 5

1

$(this) が .selectnumber スパンを参照していないと想定する必要があります。

それは正解です。this単にそれらの関数を呼び出しているという理由だけで、選択した要素を参照することを期待しています。ただし、引数を関数に渡すだけです。その時点では、関数を呼び出しているオブジェクトとは関係がないため、あまり意味がありません。

ただし、.text()jQuery メソッドに関数を渡すことthisできます。これにより、特定の一致した要素を参照することができます。

$(".selectnumber").text(function () {
    return $(this).parent().find('select').children(':selected').text()
});
于 2013-05-24T10:15:15.937 に答える
0

.html()の代わりに使用する必要がありますtext()。選択が変更されるたびにスパンの更新も必要になる場合があります。

    $(".selectnumber").html($('#number_of_cards_required').val());


       $('#number_of_cards_required').change(function(){
    $(".selectnumber").html($('#number_of_cards_required').val());
});

このjsfiddleを見てください

于 2013-05-24T10:14:39.173 に答える
0
$(function() {

//initial loading
$(".selectnumber").text($(".selectnumber").parent().find('select').children(':selected').text());  

//changing span if select changes

$("select").change(function() {
$(".selectnumber").text($(this).parent().find('select').children(':selected').text());        
    })
})

http://jsfiddle.net/ACf4Y/

于 2013-05-24T10:15:16.807 に答える