【问题标题】:How to Get id's of all inputs inside the form?如何获取表单内所有输入的ID?
【发布时间】:2011-02-28 05:07:25
【问题描述】:

如何获取数组中表单内所有输入元素的id?

【问题讨论】:

  • +1 好问题。对于那些投反对票的人:当你刚加入 SO 时,你是否受到了同样的热烈欢迎?
  • 为什么这个问题被否决了?
  • 投反对票的一个可能原因是标题太长而问题太短。当它们相同时,通常是这种情况。
  • 你可能想解释一下你想用这些 id 做什么,因为通常当你想要一个 id 数组时,实际上最好有一个实际元素的数组

标签: jquery arrays forms input


【解决方案1】:

有点意思...

<script src="../../Scripts/jquery-1.4.2.min.js"></script>

<script type="text/javascript">

    $(document).ready(function ()
    {
         // Get all the inputs into an array...
         var $inputs = $('#myForm :input');

         // An array of just the ids...
         var ids = {};

         $inputs.each(function (index)
         {
             // For debugging purposes...
             alert(index + ': ' + $(this).attr('id'));

             ids[$(this).attr('name')] = $(this).attr('id');
         });
    });


</script>

【讨论】:

    【解决方案2】:
    $ids = $('#myform input[id]').map(function() {
      return this.id;
    }).get();
    

    【讨论】:

    • +1 - map() 是要走的路,虽然如果有 input 元素没有 ID(可能是提交),你最终会得到一个空条目在数组中。您可能希望将选择器更改为:$('#test input[id]'),或者至少提供如下测试:if(this.id) return this.id;
    【解决方案3】:

    您可以使用更精确的选择器来缩小搜索范围:表单输入用于具有 id 的属性选择器

    $(document).ready(function() {
        $('form input[id]').each(function() {
            formId.push(J(this).attr('id'));
    });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 2023-01-12
      • 2015-04-06
      • 2019-08-17
      • 2017-10-27
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多