2012-07-19 84 views
2

我得到一個ASP.NET列表框,並在更改時,我需要顯示(單個或多個)警報中的(單個或多個)選定的文本。警報數量應等於所選項目的數量。我嘗試了下面的代碼,在那裏我得到了一個額外的警報,顯示ListBox中的第一個項目。我哪裏做錯了?jQuery 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); 
      } 
     }); 
    }); 
}); 

請幫忙。

謝謝。

+0

似乎運作良好,http://jsfiddle.net/9zthu/2/ – ocanal 2012-07-19 13:51:02

回答

1

我認爲正在發生的事情是,你的ASP代碼被渲染時listItems,因爲這在HTML:

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

由於「選擇」屬性出現在這兩種情況下,檢查this.selected將返回如果屬實該屬性設置爲true或false,因爲「selected」以任一方式存在。

更簡單的方法來完成同樣的目標是要取代這個:

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

與此:

$('#ListBox1').find('option:selected').map(function() { 
    alert.log($(this).text()); 
});