【问题标题】:Access Global data-* attributes in javascript [duplicate]在javascript中访问全局数据-*属性[重复]
【发布时间】:2019-08-06 09:59:15
【问题描述】:

我正在尝试为 ajax 表编写一个小过滤器脚本,并尝试在有人单击元素时打开覆盖:

<div class="at-filter" data-filter-val="{some_value}" data-filter-type="{some_type}">
...
</div>

如何通过 javascript/jquery 访问数据过滤器类型和值?通过谷歌根本找不到任何东西。 我正在寻找这样的东西:

this.table.find( '.at-filter' ).each(
    function(index, element) {
        var type=$(element).data-filter-type();
        var val=$(element).data-filter-val();
        self.data.filter[type] = {};
        $(element).bind('click', {self:self, val:val, type:type}, type.openContextMenu);
    }
)

编辑:犯了错误!

【问题讨论】:

  • @StefanR - 这是一个很好的使用 DOM 的方法(这显然有效)。我在使用 jQuery 的 API 找到一个 good 时遇到了很多麻烦。我可以找到很多使用attr 和/或data 但重点不同的地方。非常令人惊讶。

标签: javascript html dom


【解决方案1】:

要获取属性值,请使用 jquery attr() 或纯 JavaScript getAttribute

但是

要检索和更改 DOM 属性,例如表单元素的选中、选择或禁用状态,请使用 .prop() 方法。

或者

在纯 JavaScript setAttribute

console.log($('.me').attr('data-attribute'));
console.log($('.me').attr('data-second-attr'));

$('.me').each(function() {
  console.log(this.getAttribute('data-attribute'));
  console.log(this.getAttribute('data-second-attr'));
  this.setAttribute('data-second-attr', 'foo-bar');
  console.log('after change', this.getAttribute('data-second-attr'));
})

$('.me').prop('data-attribute', 'baz')
console.log('after change', $('.me').prop('data-attribute'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="me" data-attribute="foo" data-second-attr="bar">yo</div>

【讨论】:

    【解决方案2】:

    你使用attr:

    var type = $(element).attr("data-filter-type");
    

    你也可以使用data:

    var type = $(element).data("filter-type"); // Read the note below, though
    

    ...但是如果您只想访问这些属性的值,则没有必要或不合适。与流行的看法相反,data is not an accessor for data-* attributes。 (既多又少。)

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2017-05-25
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多