0

您好,我有一个循环,可以在局部视图中呈现元素。这些元素是列表框,用于渲染的列表框的数量取决于局部视图本身无法访问的条件。我想要做的是找到使用 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()" })
4

1 回答 1

0

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]');
于 2012-07-27T05:13:40.607 回答