用于获取字段属性的JQuery通用工具

JQuery generic tool to get field attributes.

本文关键字:工具 JQuery 获取 字段 属性 用于      更新时间:2023-09-26

我正在尝试编写一个通用的javascript工具,用JQuery获取表单字段名称、id及其值。

<div id="StudentForm">
<div><input id='name' name='name' value='John' /></div>
</div>

例如,我想获取"StudentForm"div中的所有字段,输出其id、名称和值。如何编写通用工具包或API?

我喜欢JQuery,所以我更喜欢JQuery解决方案。

jsfiddle示例

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)

我希望这就是你想要的。。

您可以编写一个简单的jQuery插件

(function ($) {
    $.fn.getAttributes = function () {
        return [$(this).attr('id'), $(this).attr('name'), $(this).val()];
    }
}(jQuery));

像这个一样使用

$('#StudentForm').find('input').each(function () {
    alert($(this).getAttributes());
});

在这里摆弄

有关jQuery插件的更多信息,请查看此答案

jQuery提供了serialize()和serializeArray()方法,它们可以完成您想要的大部分工作。