2

ASP.NET ListBox を取得しました。変更時に、選択した (1 つまたは複数の) テキストを (1 つまたは複数の) アラートに表示する必要があります。アラートの数は、選択したアイテムの数と同じにする必要があります。次のコードを試してみましたが、ListBox の最初の項目を示す追加のアラートが表示されます。どこで私は間違えましたか?

<asp:ListBox ID="ListBox1" runat="server" Width="100px"
    SelectionMode="Multiple">
    <asp:ListItem Selected="True" Value="1">White</asp:ListItem>
    <asp:ListItem Selected="False" Value="2"> Silver </asp:ListItem>
    <asp:ListItem Value="3"> Dark Gray </asp:ListItem>
    <asp:ListItem Value="4"> Khaki </asp:ListItem>
    <asp:ListItem Value="5"> Dark Khaki </asp:ListItem>
</asp:ListBox>

$(document).ready(function () {
    $("#ListBox1 ").change(function () {
        $("option").each(function () { 
            if (this.selected) {
                alert(this.text);
            }
        });
    });
});

助けてください。

ありがとう。

4

1 に答える 1

1

あなたのaspコードがHTMLでリストアイテムを次のようにレンダリングしていると思います:

...
<option value="1" selected="true">
<option value="2" selected="false">
...

どちらの場合にも "selected" 属性が存在するため、属性が true または false に設定されている場合、 this.selected をチェックすると true が返されます。どちらにも "selected" が存在するためです。

同じ目的を達成するためのより簡単な方法は、これを置き換えることです:

$("#ListBox1 ").change(function () {
    $("option").each(function () { 
        if (this.selected) {
            alert(this.text);
        }
    });
});

これとともに:

$('#ListBox1').find('option:selected').map(function () {
  alert.log($(this).text());
});
于 2013-03-07T02:41:56.937 に答える