簡體   English   中英

ASP.Net MVC 4和Jquery選擇選項

[英]ASP.Net MVC 4 & Jquery Select option

問題:我正在建立一個動態的產品列表,其中每個產品都包含一個“產品類型”,即時遍歷每個產品,但是我需要為現有產品設置所選選項

$.each(products.All(), function(index, product) {
for(p in productList) {
                $( "#"+product.itemId+"_type" ).append($("<option/>", {
                    value: productList[g].value,
                    text: productList[g].label,
//Need to add something like if(productList[g].value == p.typeId) selected:true
                }));

}

您應該按照使用ASP.Net MVC 4的指定使用SelectList

http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist%28v=vs.118%29.aspx

兩個構造函數使您可以設置所選值。 無論如何

你可以這樣

$("<option/>").attr("selected", "selected");

要么

    $.each(products.All(), function(index, product) {
    for(p in productList) {

    // declare here a variable selectedValue

    if(productList[g].value == p.typeId){

    // set here a variable selectedValue 
    }
    else {
    // set here a variable selectedValue 
    }



                $( "#"+product.itemId+"_type" ).append($("<option/>", {
                    value: productList[g].value,
                    text: productList[g].label,
                    selected: selectedValue,
                }));

}

使用javascript嘗試一下:

<script type="text/javascript">

$.each(products.All(), function(index, product) {
     var select = document.getElementById("YourSelect");
             for(p in productList) 
               {
                   var el = document.createElement("option");
                    el.textContent =productList[g].label;
                    el.value = productList[g].value;
                    if(productList[g].value == p.typeId)
                     {
                      el.selected = true;
                     }
                    select.appendChild(el);

               }
   });
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM