我有一个asp应用程序,我必须使用javascript来获取元素的值
@for(int i=0; i< Model.Count; i++){
<input type="text" value="@Model[i].age" name="age@(i)" />
HtmlActionLink("new age","Change", new { age = "age" + i.ToString()});
}
我需要获取每个代码age
的值:new { age = "age" + i.ToString()
无效,我必须使用document.getElementsByName
方法将脚本javascript替换为
如何修改我的代码才能执行此任务?
答案 0 :(得分:2)
我只需在每个输入元素中添加一个类,赋予它一些含义(例如'input-age'):
<input class="input-age" type="text" value="@Model[i].age" name="age@(i)" />
然后您可以按类名选择所有输入,而不需要依赖视图引擎中动态分配的名称:
var ages = document.querySelectorAll('input.input-age');
或者,如果您需要找到特定年龄索引的值,而不添加类名:
var ageIndex = 4;
var age = document.querySelector('input[name="age' + ageIndex + '"]').value;
仅供参考,对于IE,由于querySelectorAll
功能,它只能在版本8或更高版本中使用,但您可以使用其他方法。
如果jQuery在桌面上,你无法改变任何东西并使用“starts with”选择器来获取所有“age”元素:
var ages = $('input[name^="age"]');
或者,在添加班级名称之后:
var ages = $('.input-age');
或者,搜索特定输入的值:
var ageIndex = 4;
var age = $('input[name="age' + ageIndex + '"]').val();
在最后一个示例中,您不需要添加类名;