【问题标题】:retrieve and loop all data- attributes starting with string in an element检索并循环元素中以字符串开头的所有数据属性
【发布时间】:2018-07-02 11:15:02
【问题描述】:

给定:

<a href="#" data-ajax-this="foo" data-ajax-that="faa" data-apple="tree" data-pear="pot"></a>

我只想检索和循环“data-ajax-this”和“data-ajax-that”。

我可以像这样循环所有数据属性:

$.each($('a').data(), function(i,v){
  console.log(i+" , "+v);
})

...我想我可以查询“i”以查看它是否在函数中包含“ajax”:

$.each($('a').data(), function(i,v){
  if(i.indexOf('ajax') !== -1){
    console.log(i+" , "+v);
  }
})

但理想情况下,我希望仅使用 .data() 进行选择。是否可以执行以下操作:

$.each($('a').data('ajax'+*), function(i,v){
  console.log(i+" , "+v);
})

谢谢

【问题讨论】:

  • 在 jQuery 中没有这样的功能(并且在 vanilla DOM API 中没有其他选择 - 当然,除了过滤掉 dataset,但这与您所展示的基本相同)。改用特定的属性命名空间怎么样?
  • 我认为没有捷径可走。但是你应该使用indexOf() == 0,所以它只匹配开头,而不是属性中的任何地方。
  • 谢谢两位。 @raina77ow 你能举个例子吗?谢谢

标签: javascript jquery custom-data-attribute


【解决方案1】:

虽然它并不优雅并且依赖于嵌套循环,但您可以完成您所追求的。

您可以使用attributes 属性并对其进行循环。

$.each($('a'), function() {
  $.each(this.attributes, function() {
    if ( this.name.indexOf('data-ajax') === 0 ) {
      // Do somethng with this.value
    }
  });
});

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 1970-01-01
    • 2016-12-04
    • 2011-04-07
    • 2017-05-26
    • 2023-04-01
    • 2021-12-26
    • 2011-06-26
    相关资源
    最近更新 更多