2012-07-27 20 views
0

你好,我有一個循環呈現局部視圖內的元素。元素是listboxesfor,呈現的listboxes的數量取決於在局部視圖本身內無法訪問的條件。我想要做的是找到通過使用JavaScript函數和可能的第一個列表框呈現的列表框的數量,然後我可以通過它們循環。另一種方法是分配一個類名,然後計數,但我不能這樣做。請幫忙。does document.getelementbytagname work for mvc listboxfor

function dosomething() { 
      var x = document.getElementsByTagName("listbox");//This line always returns O 
      alert(x.length); 
} 

@Html.ListBoxFor(model => model.ServiceTypes, new MultiSelectList(RunLog.Domain.Lists.GlobalList.PartsServiceTypes(), "ID", "Name"), new { style = "width: 200px; height: 80px;", id = "lstbox", name="listbox", onclick = "dosomething()" }) 

回答

0

HTML中沒有這樣的東西,如listbox。它根本不存在。在HTML術語中(這是您操作的內容),該元素被稱爲select,允許多選的multiple="multiple"屬性。

所以:

var x = document.getElementsByTagName("select"); 
// now when looping over this x variable make sure 
// you check for the presence of the multiple="multiple" 
// attribute which is the only thing which distinguishes 
// what you call a ListBox from a DropDown. 
for (var i = 0; i < x.length; i++)​ { 
    var element = x[i]; 
    // I am not even sure if this is a good test for the presence 
    // of the multiple attribute. Maybe it should work but can't guarantee 
    // cross browser correctness 
    if (element.multiple) { 
     // we've got a list box here 
    } 
} 

,如果你決定使用jQuery:

var listBoxes = $('select[multiple]'); 
+0

你在哪裏調用'document.getElementsByTagName( 「選擇」)'方法?你是否等待DOM被加載? – 2012-07-27 05:23:15

+0

很棒!如果我可能會問最後一件事,所有的列表框都會有相同的列表項。無論從第一個列表框中選擇什麼,都應該在列表框的其餘部分中選擇。這就是爲什麼我要循環他們。真的很感激它 – user721 2012-07-27 05:38:50