document.getelementbytagname是否适用于mvc列表框

does document.getelementbytagname work for mvc listboxfor

本文关键字:列表 mvc 适用于 getelementbytagname 是否 document      更新时间:2024-04-17

你好,我有一个循环,它在局部视图中渲染元素。元素是用于的列表框,用于渲染的列表框的数量根据局部视图本身中不可访问的条件而变化。我想做的是找到通过使用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()" })

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