【问题标题】:jQuery access input field by name[value][id]jQuery 通过 name[value][id] 访问输入字段
【发布时间】:2011-04-26 23:48:03
【问题描述】:

我有一些这样的 HTML 代码:

<input id="fieldname-1" name="field_name[value][1]" value="1" type="checkbox" />
<input id="fieldname-2" name="field_name[value][2]" value="2" type="checkbox" />
<input id="fieldname-3" name="field_name[value][3]" value="3" type="checkbox" />

我想用 jQuery 来访问它:

$('input[field_name]').change( function() { dosomething(); });

我无法通过调用$('.classname') 添加类字段来执行此操作,因为它是由 Drupal 的 cck 模块呈现的,我不想将其添加到主题层。

最好的办法是让我的模块为每个字段添加一个类。但更快的解决方案是知道如何通过 jQuery 访问这些字段

【问题讨论】:

  • 为什么不通过id访问?
  • 因为 id 只能访问一个字段。我希望我的 jquery 在多个字段上运行(忘了在我的问题中说)另外,当我添加字段时,我必须重写 jQuery 代码

标签: jquery drupal cck checkbox inputbox


【解决方案1】:

您可以使用the attribute equals selectorname 属性进行完全匹配。

$('input[name="field_name[value][2]"]').change(func...

或者如果您想要所有field_name 开头的&lt;input&gt; 元素,您可以使用the attribute starts with selector

$('input[name^=field_name]').change(func...

这将选择name 属性以field_name 开头的所有&lt;input&gt; 元素。

此外,如果它们都是复选框,您可以在选择器中使用:checkbox 而不是input

此外,如果需要,您可以使用相同的方法,但使用 ID 属性。

$('input[id^=fieldname]').change(func...

【讨论】:

    【解决方案2】:

    看来你需要一个模糊选择器:[name^=value] 这样的事情可能就足够了:

    $('[name^=field_name]').each(function(index,element){
      $(element).change(function(){})
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2021-04-13
      • 2016-11-09
      相关资源
      最近更新 更多