2017-05-04 146 views
1

我有一個DropBox有4個選項。選項取自我創建的列表。 這是列表和Dropbox的MVC剃鬚刀中的DropBox

<div> 
     @{ 
    List<SelectListItem> listItems= new List<SelectListItem>(); 
    listItems.Add(new SelectListItem 
     { 
      Text = "SearchInputPosition", 
      Value = "1" 
     }); 
    listItems.Add(new SelectListItem 
     { 
      Text = "MissingNumber", 
      Value = "2" 

     }); 
    listItems.Add(new SelectListItem 
     { 
      Text = "ClimbStaircase", 
      Value = "3" 
     }); 

} 
     </div> 

@Html.DropDownListFor(model => model.textProblem, listItems, "-- Select Status --", new { id = "c", @onchange ="changeText(c)"}) 

如果我選擇我想顯示一些文本用javascript函數Dropbox的值,但它顯示未定義。

<script> 
       var data = {   
      "1": "Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.", 
      "2": "You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?", 
      "3": "Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.", 
      } 
      function changeText(id) { 
       document.getElementById("content").innerHTML = data[id]; 
       } 
    </script> 
<div id="content"></div> 

我該怎麼做才能解決這個問題?

回答

1

您可以爲select元素綁定change事件處理函數並使用其值。

<script> 
     var data = {   
     "1": "Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.", 
     "2": "You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?", 
     "3": "Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.", 
     } 
     var select=document.getElementById('textProblem'); 
     select.onchange=function(){ 
      document.getElementById("content").innerHTML = data[this.value]; 
     } 
</script> 
+0

它沒有做任何事情。至少不顯示undefined :) –

+0

@GeorgeGreat,刪除舊的更改事件 –

+0

從@ Html.DropDownListFor(model => model.textProblem,listItems,「 - Select Status - 」,new {id =「c」,@ onchange =「changeText(c)」}) –