我正在尝试编写一个通用的javascript工具,以使用JQuery获取表单字段名称,id及其值。
<div id="StudentForm">
<div><input id='name' name='name' value='John' /></div>
</div>
例如,我想获取'StudentForm'div中的所有字段,输出其id,name及其值。如何编写通用工具包或API?
我喜欢JQuery,所以我更喜欢JQuery解决方案。
答案 0 :(得分:0)
HTML:
<div id="StudentForm">
<div><input id='name' name='name' value='John' /></div>
<div><input id='name1' name='name1' value='John1' /></div>
<div><input id='name2' name='name2' value='John2' /></div>
<div><input id='name3' name='name3' value='John3' /></div>
</div>
jQuery的:
var all = ''; //if you need all at once
$('#StudentForm > div > input').each(
function(){
if(all.length == 0){
all = $(this).val();
}else{
all = all + ':' + $(this).val() ;
}
alert( 'value : '+$(this).val()+'\n'+
'name : '+$(this).attr('id')+'\n'+
"use $(this).attr('any atribute') for any other attr you need"
);
})
alert(all)
我希望这就是你要找的......
答案 1 :(得分:0)
您可以编写一个简单的jQuery插件
(function ($) {
$.fn.getAttributes = function () {
return [$(this).attr('id'), $(this).attr('name'), $(this).val()];
}
}(jQuery));
并像这样使用
$('#StudentForm').find('input').each(function () {
alert($(this).getAttributes());
});
有关jQuery插件的更多信息,请查看this answer
答案 2 :(得分:0)
jQuery提供了serialize()和serializeArray()方法,可以完成您正在寻找的大部分内容。