1
  <select id="testSelection">
           <option> test1 </option> 
           <option> test2 </option> 
           <option> test3 </option> 
           <option> test4 </option> <--- selected this one from the pull down menu 
           <option> test5 </option> 
           <option> test6 </option> 
  </select>

             $("#testSelection").change(function()
             {
                    alert($(this).text());
             });

奇妙なことに、警告メッセージにはすべての選択が表示されますが、test4 テキストのみに表示されることを期待していました。

4

3 に答える 3

5
<select id="testSelection">
    <option value="1">test1</option>
    <option value="2">test2</option>
    .....
</select> 

それは本当にあなたが望むものに依存します:

$("#testSelection").on('change', function() {
    // if you just want the text/html inside the select (ie: test1, test2, etc)
    alert($(this).find('option:selected').text()); 

    // or you want the actual value of the option <option value="THISHERE">
    alert($(this).val()); 
});​

jsFiddle デモ

于 2012-08-22T19:23:12.030 に答える
1

val()関数ではなく、関数を使用する必要がありtext()ます。

$("#testSelection").change(function()
{
    alert($(this).val());
});​
于 2012-08-22T19:24:07.617 に答える
0

$(this).text()要素 (この場合は要素) 内のすべてのテキストを返しますselect。それがあなたが得る理由です"test1 test2 ..."

選択したオプションのテキストが必要であると仮定します。

$(this).find(':selected').text()

選択したオプションの値属性が必要な場合は、@ mcpDESIGNS の回答が機能します。ただし、次のように要素にvalue属性を追加する必要があることに注意してください。option

<option value="test4">test4</option>
于 2012-08-22T19:24:27.697 に答える