jQuery 抓取动态数据 * 属性的值

jQuery grabbing value of a dynamic data-* attribute

本文关键字:属性 数据 抓取 动态 jQuery      更新时间:2023-09-26

在jQuery点击事件侦听器内部,我有一些这样的代码:

function (evt) {
  evt.preventDefault();
  var reportbox = $(this).closest('.activityItem');
  var id = reportbox.data('questionId');
  ...
}

这适用于data-question-id属性,但我现在正在泛化函数,我需要从以下任何一项中获取值:

data-question-id
data-answer-id
data-comment-id
data-user-id
data-company-id

最好的方法是什么?

如果您知道这些属性中只有一个将存在,并且您想要检索该单个值,则可以使用以下命令:

var element = $(el);
var dataAttrs = ['question-id', 'answer-id', 'comment-id', 'user-id', 'company-id'];
var data = getUnknownAttr(element, dataAttrs);

function getUnknownAttr(element, potentialAttrs) {      
    var $element = element instanceof $ ? element : $(element);
    var result = null;
    potentialAttrs.forEach(function (attr) {
        var temp = $element.data(attr);
        if (typeof temp !== 'undefined') {
            result = temp;
        }
    });
    return result;
}

正如 Brian 指出的那样,您可以访问 dataset 属性来检索元素的所有data-*属性:

$('.activityItem').each(function () {
  var dataAttributes = this.dataset;
  Object.keys(dataAttributes).forEach(function (key) {
    console.log(key, dataAttributes[key]); // key, value
  });
});

由于您只需要第一个数据属性,因此您可以简单地使用:

var dataAttributes = this.dataset;
var id = dataAttributes[Object.keys(dataAttributes)[0]];

请务必注意,dataset 属性返回不带 data 前缀的驼峰大小写的属性名称。换句话说,data-question-id将是questionId.

如果要检索元素的所有属性,请访问 attributes 属性并检查哪些属性以 data-* 开头,以 -id 结尾。它肯定更冗长,但在其他情况下可能会更好。

$('.activityItem').each(function () {
  var attributes = this.attributes;
  Object.keys(attributes).forEach(function (key) {
    var attribute = attributes[key];
    if (/^data-.*-id$/.test(attribute.name)) {
      console.log(attribute.name, attribute.value);
    }
  })
});

我只是想到了我正在寻找的东西。我想我的问题让你感到困惑,但这就是我想要的:

$('#test').children().each(function () {
  var reportbox = $(this);
  var id = reportbox.data(Object.keys(reportbox.data())[0]);
  
  reportbox.text(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <div data-question-id="1"></div>
  <div data-answer-id="2"></div>
  <div data-comment-id="3"></div>
  <div data-user-id="4"></div>
  <div data-company-id="5"></div>
</div>

重点线是:

var id = reportbox.data(Object.keys(reportbox.data())[0]);

编辑

或者,由于@Brian的评论,我可以将其重写为:

var id = this.dataset(Object.keys(this.dataset)[0]);