首页 > 解决方案 > 获取包含它的最接近元素的特定数据属性的值 TypeError

问题描述

在我的库中,我想编写一个小函数closest(),尤其是获取特定data-attribut的最接近元素的值,因为在我的应用程序中,我需要经常使用它。:D

但我只被控制台告知:

TypeError:x.getAttribute 不是函数

var $ = function(s) {
  var x;
  var obj = {
    myLib(s) {
      return x || querySelectorAll(s);
    },
    myFunction(s) {
      if (s.startsWith('data-')) { // in this block is sth. wrong
        x = [x[0].closest('*["' + s + '"]')];
        return x.getAttribute(s);
      } else {
        x = [x[0].closest(s)];
        return this;
      }
    }
  };
  x = obj.myLib(s);
  return obj;
};

////////// usage examples

// get the value of attribute "data-wrestler"
var dv = $('.kilo').myFunction('data-wrestler');
console.log(dv);

// select the closest element by selector
var ce = $('.kilo').myFunction('.uniform');
console.log(ce);

// would select the closest element with specific data-attribut by selector
var da = $('.kilo').myFunction('*["data-wrestler"]');
console.log(da);
<div id="foxtrott">
  foxtrott
  <div class="uniform" data-wrestler="hulkster">
    uniform
    <div class="charlie">
      charlie
      <div class="kilo">
        kilo
      </div>
    </div>
  </div>
</div>

标签: javascriptclosestselectors-apigetattribute

解决方案


  1. 报价[data-wrestler]- 删除它们 x = [x[0].closest('[' + s + ']')];

  2. 您使用 document.querySelectorAll - 它返回一个集合,因此您需要使用 [0]

    返回 x[0].getAttribute(s);

或更改为 document.querySelector


推荐阅读