【问题标题】:Jquery name selector with array带有数组的 Jquery 名称选择器
【发布时间】:2016-10-10 21:05:33
【问题描述】:

我正在尝试使用 jQuery 获取 2 个输入的值,但我们用于复选框的数组选择器不起作用。如何获取下面示例代码的值。

<input name="person[name]">
<input name="person[age]">

<script>
    $("input[name='person[]']").val();
</script>

【问题讨论】:

  • 好吧,对于初学者,对于您作为示例显示的任何一个元素,[name] 属性的值都不是 person[]。您是否尝试过其他方法或阅读过 jQuery API?
  • 我在互联网上搜索了它,但找不到解决方案。这就是我在这里问的原因。关于API没有从头到尾阅读。

标签: javascript jquery jquery-selectors


【解决方案1】:

使用组合的 attribute starts withattribute ends with 选择器。最后使用map() 方法迭代元素并生成一个值数组。如果你只是想遍历它们,那么each() 方法就足够了,this 可以用来引用回调中元素的 dom 对象。

$("input[name^='person['][name$=']']")

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="person[name]">
<input name="person[age]">

<script>
  console.log(
    $("input[name^='person['][name$=']']").map(function() {
      return this.value
    }).get()
  )
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="person[name]">
<input name="person[age]">

<script>
  $("input[name^='person['][name$=']']").each(function() {
    console.log(this.value);
  })
</script>

【讨论】:

    【解决方案2】:

    您可以使用*= 进行遏制。或 ^= 开始。

    示例

    $("input[name*='person['").each(function(){
      console.log($(this).val());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input name="person[name]" value="test">
    <input name="person[age]" value="ok">

    【讨论】:

      【解决方案3】:
      $("input[type='checkbox'][name='ProductCode']").each(function(){ ...
      

      【讨论】:

      • 请解释一下你的答案
      猜你喜欢
      • 2011-01-21
      • 2013-02-05
      • 2011-12-13
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2016-06-14
      相关资源
      最近更新 更多