document.getelementsbytagname为mvc listboxfor工作

时间:2012-07-27 05:11:39

标签: javascript asp.net-mvc-3

你好我有一个循环,它在局部视图中呈现元素。元素是listboxesfor,渲染列表框的数量取决于在局部视图本身内无法访问的条件。我想要做的是找到使用javascript函数和可能的第一个列表框呈现的列表框的数量,然后我可以循环它们。另一种方法是分配一个类名然后计数,但我不能这样做。请帮忙。

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()" })

1 个答案:

答案 0 :(得分:0)

HTML中没有listbox这样的东西。它根本就不存在。在HTML术语中(这是你用hjavascript操作的),该元素被称为selectmultiple="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]');